Question:To test whether two link list have common nodes or not?
Hints:-> There may be more then 1 common nodes
-> The length of both the link list might not be same
Constraints:-> Time & Space complexity to be minimal
Example 1:List 1: 1-2-3-4-5-6-7
List 2: a-b-c-6-7
Answer: Common nodes from "Node 6"
Example 2:List 1: 1-2-3-4-5-6-7
List 2: a-b-c-d-e
Answer: No common nodes
Answer:-> Take two pointers, each pointing to head of each list
-> Take two counter variables for each list to store the length of list
-> Traverse both the list and increment the count on each node traversal
-> Get the length difference by subtracting the counter with higher value to lower one and put to some difference variable
-> Increment the pointer "difference variable" times whose length is greater
-> Increment both the pointers and compare at each iteration, till any node reaches the tail
If they reach tail and both pointers didn't got common value -> No common nodes
Else -> Common nodes from that node
Complexity:Time: O(2N) -> O(N) , where N represents longest link list length
Space: O(3) -> O(1)
Example 1:List 1: 1-2-3-4-5-6-7
List 2: a-b-c-6-7
Answer: Common nodes from "Node 6"
Tracing:See the previous post.
Example 2:List 1: 1-2-3-4-5-6-7
List 2: a-b-c-d-e
Answer: No common nodes
Tracing:Step 1:
-> Let Pointer 1 points to head of List 1 and counter is Length 1
-> Let Pointer 2 points to head of List 2 and counter is Length 2
Step 2:
-> The Length 1 value will be: 7
-> The Length 2 value will be: 5
-> Difference variable value will be: 2
Step 3:
-> List 1 length is bigger, hence Pointer 1 will be incremented two time to point to Node 2
Step 4:
Movement of Pointer 1: 3-4-5-6-7
Movement of Pointer 2: a-b-c-d-e
We reached the tail, hence no common node
Answer:No common nodes