VOOZH about

URL: https://www.geeksforgeeks.org/dsa/union-and-intersection-of-two-linked-list-using-hashing/

⇱ Intersection of two Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Intersection of two Linked List

Last Updated : 19 Apr, 2026

Given two singly distinct linked lists, create a new linked list that contains the intersection of elements present in both lists.

Note: The order of nodes in this list should be the same as they nodes appear in LinkedList1.

Examples:

Input: LinkedList1: 9->6->4->2->3->8 , LinkedList2: 1->2->8->6
👁 Image
Output: 6->2->8
Explanation: Nodes 6, 2 and 8 are common in both of the lists and the order will be according to LinkedList1.

Input: LinkedList1: 5->3->1->13->14 , LinkedList2: 3->13
👁 Image

Output: 3->13
Explanation: Nodes 3 and 13 are common in both of the lists and the order will be according to LinkedList1.

Input:
head1: 4 -> 2 -> 4 -> 1 -> 2 -> 8
head2: 2 -> 4 -> 6 -> 2 -> 4
Output:
Intersection: 4 -> 2
Explanation: Common elements in both lists are 4 and 2. Even though they appear multiple times, each element is included only once in the intersection list.

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

Traverse the first linked list and for each element, check whether it exists in the second linked list. If yes and not already added, insert it into the result list.


Output
Intersection: 6 2 8 

[Better Approach] Using Sorting - O(n Log n + m Log m) Time and O(n + m) Space

Sort both linked lists and use two pointers to efficiently find common elements.

Steps

  1. Sort both lists
  2. Compare nodes one by one. If equal, add to the result. Else more pointer in the linked list having smaller value.
  3. Continue until one list ends.
  4. Return result

Output
Intersection: 2 6 8 

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

Store elements of the first list in a hash set. Then traverse the second list and check if each element exists in the set. Add to result while avoiding duplicates.

Algorithm:

  1. Create an empty Hash Set to store nodes in linkedList1 and initialize result as NULL.
  2. Traverse second list and insert all values into set
  3. Initialize tail as NULL and traverse first list
  4. If current value exists in set, it is common. Add it to result list
  5. Remove it from set to avoid duplicates and move to next node
  6. Return result list

Output
Intersection: 4 2 

Time Complexity: O(m+n) , where m and n are number of elements present in first and second lists respectively.
Auxiliary Space: O(m), set stores elements of one list only

Comment