The Wayback Machine - https://web.archive.org/web/20240925093813/https://www.geeksforgeeks.org/union-and-intersection-of-two-linked-lists/
Open In App

Union and Intersection of two Linked Lists

Last Updated : 10 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two linked lists contains distinct node values.
Note: The order of elements in output lists doesn’t matter. 

Example:

Input:
head1: 10 -> 15 -> 4 -> 20
head2: 8 -> 4 -> 2 -> 10
Output:
Union: 10 -> 15 -> 4 -> 20 -> 8 -> 2
Intersection: 10 -> 4
Explanation: In these two lists 4 and 10 nodes are common. The union lists contain all the unique nodes of both lists.

Input:
head1 : 1 -> 2 -> 3 -> 4
head2 : 3 -> 4 -> 8 -> 10
Output:
Union: 1 -> 2 -> 3 -> 4 -> 8 -> 10
Intersection: 3 -> 4
Explanation: In these two lists 4 and 3 nodes are common. The union lists contain all the unique nodes of both lists.

[Naive Approach] Using Two Nested Loops – O(n * m) Time and O(n + m) Space:

The idea is to traverse both linked lists and check each element’s presence in the result list to avoid duplicates. For the union, we add all unique elements from both lists. For the intersection, we only add elements that are present in both lists.

  • For union – We traverse both linked lists one by one, and for each element check if the element is already present in the resulting union list, If the element is not present, insert it into the union list.
  • For Intersection – We traverse the first linked list, and for each element check if the element is present in the second linked list and not already in the resulting intersection list then we will insert it into the intersection list.

Below is the implementation of the above approach: 

C++
// C++ program to find union and intersection of two 
// unsorted linked lists

#include <iostream>
using namespace std;

class Node {
public:
    int data;   
    Node* next;  

    Node(int x) {
        data = x;
        next = nullptr;
    }
};

// Function to check if a value is present in the linked list
bool isPresent(Node* head, int value) {
    Node* curr = head;
    while (curr != nullptr) {
        if (curr->data == value) {
            return true;
        }
        curr = curr->next;
    }
    return false;
}

// Function to find the union of two linked lists
Node* findUnion(Node* head1, Node* head2) {
    Node* result = nullptr;
    Node* tail = nullptr;
    Node* curr1 = head1, *curr2 = head2;

    // Insert all elements from the first list 
  // into the result list
    while (curr1 != nullptr) {
        if (!isPresent(result, curr1->data)) {
            Node* newNode = new Node(curr1->data);
            if (result == nullptr) {
                result = newNode;
                tail = result;
            } else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        curr1 = curr1->next;
    }

    // Insert elements from the second list into the 
    // result list if they are not already present
    while (curr2 != nullptr) {
        if (!isPresent(result, curr2->data)) {
            Node* newNode = new Node(curr2->data);
            if (result == nullptr) {
                result = newNode;
                tail = result;
            } else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        curr2 = curr2->next;
    }

    return result;
}

// Function to find the intersection of two linked 
// lists using brute force
Node* findIntersection(Node* head1, Node* head2) {
    Node* result = nullptr;
    Node* tail = nullptr;
    Node* curr1 = head1, *curr2 = head2;

    // For each element in the first list, check if 
      // it is present in the second list
    while (curr1 != nullptr) {
        if (isPresent(curr2, curr1->data) 
            && !isPresent(result, curr1->data)) {
          
            Node* newNode = new Node(curr1->data);
            if (result == nullptr) {
                result = newNode;
                tail = result;
            } else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        curr1 = curr1->next;
    }

    return result;
}

void printList(Node* head) {
    Node* curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {
  
    // Creating two hardcoded linked lists
    Node* head1 = nullptr;
    Node* head2 = nullptr;

    // Insert elements into the first linked list
    // 10 -> 15 -> 4 -> 20
    head1 = new Node(10);
    head1->next = new Node(15);
    head1->next->next = new Node(4);
    head1->next->next->next = new Node(20);

    // Insert elements into the second linked list
    // 8 -> 4 -> 2 -> 10
    head2 = new Node(8);
    head2->next = new Node(4);
    head2->next->next = new Node(2);
    head2->next->next->next = new Node(10);

    Node* unionList = findUnion(head1, head2);
    Node* intersectionList = findIntersection(head1, head2);

    cout << "Union: ";
    printList(unionList);

    cout << "Intersection: ";
    printList(intersectionList);

    return 0;
}
C
// C program to find union and intersection of two 
// unsorted linked lists

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;   
    struct Node* next;  
};

struct Node* createNode(int x);

// Function to check if a value is present in the linked list
int isPresent(struct Node* head, int value) {
    struct Node* curr = head;
    while (curr != NULL) {
        if (curr->data == value) {
            return 1;
        }
        curr = curr->next;
    }
    return 0;
}

// Function to find the union of two linked lists
struct Node* findUnion(struct Node* head1, struct Node* head2) {
    struct Node* result = NULL;
    struct Node* tail = NULL;
    struct Node* curr1 = head1;
    struct Node* curr2 = head2;

    // Insert all elements from the first list into the result list
    while (curr1 != NULL) {
        if (!isPresent(result, curr1->data)) {
            struct Node* newNode = createNode(curr1->data);
            if (result == NULL) {
                result = newNode;
                tail = result;
            } else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        curr1 = curr1->next;
    }

    // Insert elements from the second list into the 
    // result list if they are not already present
    while (curr2 != NULL) {
        if (!isPresent(result, curr2->data)) {
            struct Node* newNode = createNode(curr2->data);
            if (result == NULL) {
                result = newNode;
                tail = result;
            } else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        curr2 = curr2->next;
    }

    return result;
}

// Function to find the intersection of two linked
// lists using brute force
struct Node* findIntersection(struct Node* head1, struct Node* head2) {
    struct Node* result = NULL;
    struct Node* tail = NULL;
    struct Node* curr1 = head1;
    struct Node* curr2 = head2;

    // For each element in the first list, check if it is
      // present in the second list
    while (curr1 != NULL) {
        if (isPresent(curr2, curr1->data) 
            && !isPresent(result, curr1->data)) {
          
            struct Node* newNode = createNode(curr1->data);
            if (result == NULL) {
                result = newNode;
                tail = result;
            } else {
                tail->next = newNode;
                tail = newNode;
            }
        }
        curr1 = curr1->next;
    }

    return result;
}

void printList(struct Node* head) {
    struct Node* curr = head;
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("\n");
}

struct Node* createNode(int x) {
    struct Node* newNode = 
      (struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->next = NULL;
    return newNode;
}

int main() {
    // Creating two hardcoded linked lists

    // Insert elements into the first linked list
    // 10 -> 15 -> 4 -> 20
    struct Node* head1 = createNode(10);
    head1->next = createNode(15);
    head1->next->next = createNode(4);
    head1->next->next->next = createNode(20);

    // Insert elements into the second linked list
    // 8 -> 4 -> 2 -> 10
    struct Node* head2 = createNode(8);
    head2->next = createNode(4);
    head2->next->next = createNode(2);
    head2->next->next->next = createNode(10);

    struct Node* unionList = findUnion(head1, head2);
    struct Node* intersectionList = findIntersection(head1, head2);

    printf("Union: ");
    printList(unionList);

    printf("Intersection: ");
    printList(intersectionList);

    return 0;
}
Java
// Java program to find union and intersection of two 
// unsorted linked lists

class Node {
    int data;
    Node next;

    Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {

    // Function to check if a value is present in the linked list
    static boolean isPresent(Node head, int value) {
        Node curr = head;
        while (curr != null) {
            if (curr.data == value) {
                return true;
            }
            curr = curr.next;
        }
        return false;
    }

    // Function to find the union of two linked lists
    static Node findUnion(Node head1, Node head2) {
        Node result = null;
        Node tail = null;
        Node curr1 = head1, curr2 = head2;

        // Insert all elements from the first 
          // list into the result list
        while (curr1 != null) {
            if (!isPresent(result, curr1.data)) {
                Node newNode = new Node(curr1.data);
                if (result == null) {
                    result = newNode;
                    tail = result;
                } else {
                    tail.next = newNode;
                    tail = newNode;
                }
            }
            curr1 = curr1.next;
        }

        // Insert elements from the second list into the 
        // result list if they are not already present
        while (curr2 != null) {
            if (!isPresent(result, curr2.data)) {
                Node newNode = new Node(curr2.data);
                if (result == null) {
                    result = newNode;
                    tail = result;
                } else {
                    tail.next = newNode;
                    tail = newNode;
                }
            }
            curr2 = curr2.next;
        }

        return result;
    }

    // Function to find the intersection of two linked 
      // lists using brute force
    static Node findIntersection(Node head1, Node head2) {
        Node result = null;
        Node tail = null;
        Node curr1 = head1, curr2 = head2;

        // For each element in the first list, check if it 
          // is present in the second list
        while (curr1 != null) {
            if (isPresent(curr2, curr1.data) 
                && !isPresent(result, curr1.data)) {
              
                Node newNode = new Node(curr1.data);
                if (result == null) {
                    result = newNode;
                    tail = result;
                } else {
                    tail.next = newNode;
                    tail = newNode;
                }
            }
            curr1 = curr1.next;
        }

        return result;
    }

    static void printList(Node head) {
        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
      

        // Insert elements into the first linked list
        // 10 -> 15 -> 4 -> 20
        Node head1 = new Node(10);
        head1.next = new Node(15);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(20);

        // Insert elements into the second linked list
        // 8 -> 4 -> 2 -> 10
        Node head2 = new Node(8);
        head2.next = new Node(4);
        head2.next.next = new Node(2);
        head2.next.next.next = new Node(10);

        Node unionList = findUnion(head1, head2);
        Node intersectionList = findIntersection(head1, head2);

        System.out.print("Union: ");
        printList(unionList);

        System.out.print("Intersection: ");
        printList(intersectionList);
    }
}
Python
# Python program to find union and intersection of two 
# unsorted linked lists

class Node:
    def __init__(self, x):
        self.data = x
        self.next = None

# Function to check if a value is present in the linked list
def isPresent(head, value):
    curr = head
    while curr is not None:
        if curr.data == value:
            return True
        curr = curr.next
    return False

# Function to find the union of two linked lists
def findUnion(head1, head2):
    result = None
    tail = None
    curr1, curr2 = head1, head2

    # Insert all elements from the first list into the result list
    while curr1 is not None:
        if not isPresent(result, curr1.data):
            newNode = Node(curr1.data)
            if result is None:
                result = newNode
                tail = result
            else:
                tail.next = newNode
                tail = newNode
        curr1 = curr1.next

    # Insert elements from the second list into the 
    # result list if they are not already present
    while curr2 is not None:
        if not isPresent(result, curr2.data):
            newNode = Node(curr2.data)
            if result is None:
                result = newNode
                tail = result
            else:
                tail.next = newNode
                tail = newNode
        curr2 = curr2.next

    return result

# Function to find the intersection of two 
# linked lists using brute force
def findIntersection(head1, head2):
    result = None
    tail = None
    curr1, curr2 = head1, head2

    # For each element in the first list, 
    # check if it is present in the second list
    while curr1 is not None:
        if isPresent(curr2, curr1.data) \
        and not isPresent(result, curr1.data):
          
            newNode = Node(curr1.data)
            if result is None:
                result = newNode
                tail = result
            else:
                tail.next = newNode
                tail = newNode
        curr1 = curr1.next

    return result

def printList(head):
    curr = head
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.next
    print()

if __name__ == "__main__":
  
    # Creating two hardcoded linked lists

    # Insert elements into the first linked list
    # 10 -> 15 -> 4 -> 20
    head1 = Node(10)
    head1.next = Node(15)
    head1.next.next = Node(4)
    head1.next.next.next = Node(20)

    # Insert elements into the second linked list
    # 8 -> 4 -> 2 -> 10
    head2 = Node(8)
    head2.next = Node(4)
    head2.next.next = Node(2)
    head2.next.next.next = Node(10)

    unionList = findUnion(head1, head2)
    intersectionList = findIntersection(head1, head2)

    print("Union: ", end="")
    printList(unionList)

    print("Intersection: ", end="")
    printList(intersectionList)
C#
// C# program to find union and intersection of two 
// unsorted linked lists

using System;

class Node {
    public int data;
    public Node next;

    public Node(int x) {
        data = x;
        next = null;
    }
}

class GfG {

    // Function to check if a value is present in the linked list
    static bool IsPresent(Node head, int value) {
        Node curr = head;
        while (curr != null) {
            if (curr.data == value) {
                return true;
            }
            curr = curr.next;
        }
        return false;
    }

    // Function to find the union of two linked lists
    static Node FindUnion(Node head1, Node head2) {
        Node result = null;
        Node tail = null;
        Node curr1 = head1, curr2 = head2;

        // Insert all elements from the first list into the result list
        while (curr1 != null) {
            if (!IsPresent(result, curr1.data)) {
                Node newNode = new Node(curr1.data);
                if (result == null) {
                    result = newNode;
                    tail = result;
                } else {
                    tail.next = newNode;
                    tail = newNode;
                }
            }
            curr1 = curr1.next;
        }

        // Insert elements from the second list into the 
        // result list if they are not already present
        while (curr2 != null) {
            if (!IsPresent(result, curr2.data)) {
                Node newNode = new Node(curr2.data);
                if (result == null) {
                    result = newNode;
                    tail = result;
                } else {
                    tail.next = newNode;
                    tail = newNode;
                }
            }
            curr2 = curr2.next;
        }

        return result;
    }

    // Function to find the intersection of two 
      // linked lists using brute force
    static Node FindIntersection(Node head1, Node head2) {
        Node result = null;
        Node tail = null;
        Node curr1 = head1, curr2 = head2;

        // For each element in the first list, check 
          //if it is present in the second list
        while (curr1 != null) {
            if (IsPresent(curr2, curr1.data)
                && !IsPresent(result, curr1.data)) {
              
                Node newNode = new Node(curr1.data);
                if (result == null) {
                    result = newNode;
                    tail = result;
                } else {
                    tail.next = newNode;
                    tail = newNode;
                }
            }
            curr1 = curr1.next;
        }

        return result;
    }

    static void PrintList(Node head) {
        Node curr = head;
        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.next;
        }
        Console.WriteLine();
    }

    static void Main(string[] args) {
      
        // Creating two hardcoded linked lists

        // Insert elements into the first linked list
        // 10 -> 15 -> 4 -> 20
        Node head1 = new Node(10);
        head1.next = new Node(15);
        head1.next.next = new Node(4);
        head1.next.next.next = new Node(20);

        // Insert elements into the second linked list
        // 8 -> 4 -> 2 -> 10
        Node head2 = new Node(8);
        head2.next = new Node(4);
        head2.next.next = new Node(2);
        head2.next.next.next = new Node(10);

        Node unionList = FindUnion(head1, head2);
        Node intersectionList = FindIntersection(head1, head2);

        Console.Write("Union: ");
        PrintList(unionList);

        Console.Write("Intersection: ");
        PrintList(intersectionList);
    }
}
JavaScript
// Javascript program to find union and intersection of two 
// unsorted linked lists

class Node {
    constructor(x) {
        this.data = x;
        this.next = null;
    }
}

// Function to check if a value is present in the linked
// list
function isPresent(head, value) {
    let curr = head;
    while (curr !== null) {
        if (curr.data === value) {
            return true;
        }
        curr = curr.next;
    }
    return false;
}

// Function to find the union of two linked lists
function findUnion(head1, head2) {
    let result = null;
    let tail = null;
    let curr1 = head1, curr2 = head2;

    // Insert all elements from the first list into the
    // result list
    while (curr1 !== null) {
        if (!isPresent(result, curr1.data)) {
        
            let newNode = new Node(curr1.data);
            if (result === null) {
                result = newNode;
                tail = result;
            }
            else {
                tail.next = newNode;
                tail = newNode;
            }
        }
        curr1 = curr1.next;
    }

    // Insert elements from the second list into the
    // result list if they are not already present
    while (curr2 !== null) {
        if (!isPresent(result, curr2.data)) {
            let newNode = new Node(curr2.data);
            if (result === null) {
                result = newNode;
                tail = result;
            }
            else {
                tail.next = newNode;
                tail = newNode;
            }
        }
        curr2 = curr2.next;
    }

    return result;
}

// Function to find the intersection of two linked lists
// using brute force
function findIntersection(head1, head2) {
    let result = null;
    let tail = null;
    let curr1 = head1, curr2 = head2;

    // For each element in the first list, check if it is
    // present in the second list
    while (curr1 !== null) {
        if (isPresent(curr2, curr1.data)
            && !isPresent(result, curr1.data)) {
            let newNode = new Node(curr1.data);
            if (result === null) {
                result = newNode;
                tail = result;
            }
            else {
                tail.next = newNode;
                tail = newNode;
            }
        }
        curr1 = curr1.next;
    }

    return result;
}

function printList(head) {
    let curr = head;
    while (curr !== null) {
        console.log(curr.data + " ");
        curr = curr.next;
    }
    console.log();
}

// Insert elements into the first linked list
// 10 -> 15 -> 4 -> 20
let head1 = new Node(10);
head1.next = new Node(15);
head1.next.next = new Node(4);
head1.next.next.next = new Node(20);

// Insert elements into the second linked list
// 8 -> 4 -> 2 -> 10
let head2 = new Node(8);
head2.next = new Node(4);
head2.next.next = new Node(2);
head2.next.next.next = new Node(10);

let unionList = findUnion(head1, head2);
let intersectionList = findIntersection(head1, head2);

console.log("Union: ");
printList(unionList);

console.log("Intersection: ");
printList(intersectionList);

Output
Union: 10 15 4 20 8 2 
Intersection: 10 4 

Time Complexity: O(m * n) , where m and n are the length of the two Linked Lists.
Space Complexity: O(m + n)

[Optimal Approach] Using Sorting – O(nLogn + mLogm) Time and O(n + m) Space:

The idea is to sort the given lists using merge sort, then we linearly search both sorted lists to obtain the union and intersection. By Keeping two pointers (initially pointing to the first node of the respective lists) compare the node values :

  • If the values are equal, add the value to both the union and intersection lists, then move both pointers to the next node.
  • else if the values are not equal, insert the smaller value into the union list and move the corresponding pointer to the next node.
  • If one of the pointers becomes null, traverse the remaining nodes of the other list and add them to the union list.

Please refer to Union and Intersection of Two Linked Lists Using Merge Sort for Implemenation.

[Expected Approach] Using Hashing – O(n + m) Time and O(n + m) Space:

The idea is to use HashSet to efficiently determine the union and intersection of two linked lists.

  • For Intersection – By storing the elements of one list in a hash set, we can quickly check for the presence of elements from the second list to get Intersection.
  • For Union – By storing the elements of both list in a hash set, we can get unique elements from both lists to get union.

Please refer to Union and Intersection of Two Linked Lists Using Hashing for Implemenation.



Similar Reads

Union and Intersection of two Linked List using Merge Sort
Given two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two lists contains distinct node values. Note: The order of elements in output lists doesn't matter. Examples: Input: head1: 10 -&gt; 15 -&gt; 4 -&gt; 20head2: 8 -&gt; 4 -&gt; 2 -&gt; 10O
15+ min read
Union and Intersection of two Linked List using Hashing
Given two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two linked lists contains distinct node values.Note: The order of elements in output lists doesn’t matter. Examples: Input:head1 : 10 -&gt; 15 -&gt; 4 -&gt; 20head2 : 8 -&gt; 4 -&gt; 2 -
10 min read
Find intersection point of two Linked Lists without finding the length
There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y shaped list. Write a program to get the point where both the linked lists merge. Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 ^ | 7 -&gt; 8 -&gt; 9 Output: 4 Input: 13 -
7 min read
POTD Solutions | 19 Nov' 23 | Intersection of two sorted linked lists
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Linked List but will also help you build up problem-solving skills. POTD 19 November: Intersection of two
4 min read
Intersection of two Sorted Linked Lists
Given the head of two sorted linked lists, the task is to create a new linked list that represents the intersection of the two original lists. The new linked list should be created without modifying the original lists. Note: The elements in the linked lists are not necessarily distinct. Example: Input: head1 = 1-&gt;2-&gt;3-&gt;4-&gt;6, head2 = 2-
15+ min read
Write a function to get the intersection point of two Linked Lists
Given two singly linked lists that merge into a single Y-shaped list. The two lists initially have distinct paths but eventually converge at a common node, forming a Y-shape, the task is to find and return the node where the two lists merge. The above diagram shows an example with two linked lists having 15 as intersection point. Table of Content [
15+ min read
Javascript Program For Finding Intersection Point Of Two Linked Lists
There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge.  Above diagram shows an example with two linked lists having 15 as intersection points. Method 1(Simply use
7 min read
Javascript Program For Finding Intersection Of Two Sorted Linked Lists
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed. Example: Input: First linked list: 1-&gt;2-&gt;3-&gt;4-&gt;6Second linked list be 2-&gt;4-&gt;6-&gt;8, Output: 2-&gt;4-&gt;6.The elements
3 min read
Union and Intersection of two Graphs
Given two graphs G1 and G2, the task is to find the union and intersection of the two given graphs, i.e. (G1 ∪ G2) and (G1 ∩ G2). Examples: Input: G1 = { ("e1", 1, 2), ("e2", 1, 3), ("e3", 3, 4), ("e4", 2, 4) }, G2 = = { ("e4", 2, 4), ("e5", 2, 5), ("e6", 4, 5) }Output:G1 union G2 ise1 1 2e2 1 3e3 3 4e4 2 4e5 2 5e6 4 5G1 intersection G2 ise4 2 4Exp
12 min read
Union and Intersection of two sorted arrays
Given two sorted arrays, find their union and intersection. Example: Input: arr1[] = {1, 3, 4, 5, 7} arr2[] = {2, 3, 5, 6} Output: Union : {1, 2, 3, 4, 5, 6, 7} Intersection : {3, 5} Input: arr1[] = {2, 5, 6} arr2[] = {4, 6, 8, 10} Output: Union : {2, 4, 5, 6, 8, 10} Intersection : {6} Union of Two-Sorted Arrays using SetsThe idea of the approach i
15+ min read
Find Union and Intersection of two unsorted arrays
Given two unsorted arrays that represent two sets (elements in every array are distinct), find the union and intersection of two arrays. Example: Input : arr1[] = {7, 1, 5, 2, 3, 6}, arr2[] = {3, 8, 6, 20, 7} Output : Union : {1, 2, 3, 5, 6, 7, 8, 20} Intersection : {3, 6, 7}Note that the elements of union and intersection can be printed in any ord
15+ min read
Union By Rank and Path Compression in Union-Find Algorithm
In the previous post, we introduced union find algorithm and used it to detect cycles in a graph. We used the following union() and find() operations for subsets. C/C++ Code // Naive implementation of find int find(int parent[], int i) { if (parent[i] == -1) return i; return find(parent, parent[i]); } // Naive implementation of union() void Union(i
15+ min read
Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)
Check whether a given graph contains a cycle or not. Example: Input: Output: Graph contains Cycle. Input: Output: Graph does not contain Cycle. Prerequisites: Disjoint Set (Or Union-Find), Union By Rank and Path CompressionWe have already discussed union-find to detect cycle. Here we discuss find by path compression, where it is slightly modified t
13 min read
Find intersection of intervals given by two lists
Given two 2-D arrays which represent intervals. Each 2-D array represents a list of intervals. Each list of intervals is disjoint and sorted in increasing order. Find the intersection or set of ranges that are common to both the lists. Disjoint means no element is common in a list. Example: {1, 4} and {5, 6} are disjoint while {1, 4} and {2, 5} are
7 min read
Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
Given two sorted linked lists, construct a linked list that contains maximum sum path from start to end. The result list may contain nodes from both input lists. When constructing the result list, we may switch to the other input list only at the point of intersection (which mean the two node with the same value in the lists). You are allowed to us
14 min read
Create a linked list from two linked lists by choosing max element at each position
Given two linked list of equal sizes, the task is to create new linked list using those linked lists where at every step, the maximum of the two elements from both the linked lists is chosen and the other is skipped. Examples: Input: list1 = 5 -&gt; 2 -&gt; 3 -&gt; 8 -&gt; NULL list2 = 1 -&gt; 7 -&gt; 4 -&gt; 5 -&gt; NULL Output: 5 -&gt; 7 -&gt; 4
11 min read
Intersection point of two Linked List by marking visited nodes
Given two linked lists of size N and M consisting of positive value nodes, having a common intersection point, the task is to find the intersection point of the two linked lists where they merge. Examples: Input: L1: 3 ? 6 ? 9 ? 15 ? 30, L2: 10 ? 15 ? 30Output: 15Explanation: From the above image, the intersection point of the two linked lists is 1
7 min read
Merge odd and even positioned nodes of two Linked Lists alternately
Given two linked lists L1 and L2, the task is to print a new list obtained by merging odd position nodes of L1 with the even positioned nodes of L2 alternately. Examples: Input: L1 = 8-&gt;5-&gt;3-&gt;2-&gt;10-&gt;NULL, L2 = 11-&gt;13-&gt;1-&gt;6-&gt;9-&gt;NULLOutput: 8-&gt;13-&gt;3-&gt;6-&gt;10-&gt;NULL Explanation:The odd positioned nodes of L1 a
15 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Ratio of the distance between the centers of the circles and the point of intersection of two direct common tangents to the circles
Given two circles of given radii, such that the circles don’t touch each other, the task is to find the ratio of the distance between the centers of the circles and the point of intersection of two direct common tangents to the circles. Examples: Input: r1 = 4, r2 = 6 Output: 2:3 Input: r1 = 22, r2 = 43 Output: 22:43 Approach: Let the radii of the
5 min read
Ratio of the distance between the centers of the circles and the point of intersection of two transverse common tangents to the circles
Given two circles, of given radii, such that the circles don’t touch each other. The task is to find the ratio of the distance between the centres of the circles and the point of intersection of two transverse common tangents to the circles.Examples: Input :r1 = 4, r2 = 8 Output :1:2 Input :r1 = 5, r2 = 13 Output :5:13 Approach: Let the radii of th
5 min read
Compare two strings represented as linked lists
Given two strings, represented as linked lists (every character is a node in a linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are the same, 1 if the first linked list is lexicographically greater, and -1 if the second string is lexicographically greater. Examples: Input: list1 = g-&gt;e-
7 min read
Multiply two numbers represented as linked lists into a third list
Given two numbers represented by linked lists, write a function that returns the head of the new linked list that represents the number that is the product of those numbers. Examples: Input : 9-&gt;4-&gt;6 8-&gt;4 Output : 7-&gt;9-&gt;4-&gt;6-&gt;4 Input : 9-&gt;9-&gt;9-&gt;4-&gt;6-&gt;9 9-&gt;9-&gt;8-&gt;4-&gt;9 Output : 9-&gt;9-&gt;7-&gt;9-&gt;5-
15+ min read
First common element in two linked lists
Given two Linked Lists, find the first common element between given linked list i.e., we need to find first node of the first list which is also present in the second list. Examples: Input : List1: 10-&gt;15-&gt;4-&gt;20 Lsit2: 8-&gt;4-&gt;2-&gt;10 Output : 10 Input : List1: 1-&gt;2-&gt;3-&gt;4 Lsit2: 5-&gt;6-&gt;3-&gt;8 Output : 3 We traverse the
6 min read
Longest common suffix of two linked lists
Given two singly linked lists, find the Longest common suffix of two linked lists. If there are no common characters which are suffixes, return the minimum length of the two linked lists. Examples: Input : list1 = w -&gt; a -&gt; l -&gt; k -&gt; i -&gt; n -&gt; g list2 = l -&gt; i -&gt; s -&gt; t -&gt; e -&gt; n -&gt; i -&gt; n -&gt; g Output :i -
12 min read
Count pairs from two linked lists whose product is equal to a given value
Given two linked lists(can be sorted or unsorted) of size n1 and n2 of distinct elements. Given a value X. The problem is to count all pairs from both lists whose product is equal to the given value x. Note:The pair must have an element from each linked list. Examples: Input : list1 = 3-&gt;1-&gt;5-&gt;7 list2 = 8-&gt;2-&gt;5-&gt;3 X = 10 Output :
8 min read
Divide the given linked list in two lists of size ratio p:q
Given a linked list and two integers p and q, the task is to divide the linked list in the ratio p:q i.e. the first list contains first p nodes from the original list and the second list contains the rest of the q nodes. If the original list cannot be split in the given ratio then print -1.Examples: Input: 1 -&gt; 3 -&gt; 5 -&gt; 6 -&gt; 7 -&gt; 2
6 min read
Remove the common nodes in two Singly Linked Lists
Given two Linked Lists L1 and L2, the task is to generate a new linked list with no common elements from the given two linked lists. Example: Input: L1 = 10 -&gt; 15 -&gt; 5 -&gt; 20, L2 = 8 -&gt; 5 -&gt; 20 -&gt; 10 Output: 8 -&gt; 15 Explanation: Since both the linked list has 5, 10 and 20 in common. Therefore these elements are removed and the r
10 min read
Check whether two Linked Lists are anagrams or not
Given two strings in the form of linked lists, the task is to check if one string is the anagram of the other. Print Yes if they are, otherwise print No. Examples: Input: Linked List 1 = T-&gt;R-&gt;I-&gt;A-&gt;N-&gt;G-&gt;L-&gt;E-&gt;NULLLinked List 2 = I-&gt;N-&gt;T-&gt;E-&gt;G-&gt;R-&gt;A-&gt;L-&gt;NULLOutput: YesExplanation: The given two strin
15 min read
Check if two Circular Linked Lists are identical
Given two circular linked lists L1 and L2, the task is to find if the two circular linked lists are identical or not. Note: Head of any linked list points to any node of the respective linked list and the lists can contain duplicate elements. Examples: Input: L1: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 1 -&gt; 2 -&gt; 6 L2: 5 -&gt; 1 -&gt; 2 -&gt;
13 min read