# Find the common nodes in two singly linked list

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:

## C#

Output:

Given Linked List A:
3 4 12 10 17
Given Linked List B:
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:

## C#

Output:

Given Linked List A:
3 4 12 10 17
Given Linked List B:
10 4 8 575 34 12
Number of common node in both list is = 3

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

My Personal Notes arrow_drop_up

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.