Related Articles

# Find the common nodes in two singly linked list

• Difficulty Level : Medium
• Last Updated : 30 Jun, 2021

Given two linked list, the task is to find the number of common nodes in both singly linked list.

Examples:

Input: List A = 3 -> 4 -> 12 -> 10 -> 17, List B = 10 -> 4 -> 8 -> 575 -> 34 -> 12
Output: Number of common nodes in both list is = 3

Input: List A = 12 -> 4 -> 65 -> 14 -> 59, List B = 14 -> 15 -> 23 -> 17 -> 41 -> 54
Output: Number of common nodes in both list is = 1

Naive Approach: Compare every node of list A with every node of list B. If the node is a match then increment the count and return count after all the nodes get compared.

Below is the implementation of above approach:

## Javascript


Output:
3 4 12 10 17
10 4 8 575 34 12
Number of common node in both list is = 3

Time Complexity: O(M*N), where M is length of list A and N is length of list B
Efficient Solution: Insert all the nodes of linked list A in the unordered_set and then check for each node of linked list B in unordered_set. If found increment the count and return the count at the end.

Below is the implementation of the above approach:

## Javascript


Output:
3 4 12 10 17
10 4 8 575 34 12
Number of common node in both list is = 3

Time Complexity: O(N)
Space Complexity: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up