Intersection of Linked List

You are given two Singly Linked List of integers, which are merging at some node of a third linked list.

Your task is to find the data of the node at which merging starts. If there is no merging, return -1.

For example:-

The given Linked Lists, where a1, a2, c1 is the first linked list, b1, b2, b3, c1 is the second linked list, and c1, c2, c3 is the third linked list which are merging at node c1.

alt.txt

Input Format:
The input format contains three lines consisting of three singly-linked lists. 

All three lines contain the elements of the singly linked list separated by a single space and terminated by -1.  

So first linked list would contain
       a1, a2, ...an, c1, -1. 

Similarly, the second line would contain
       b1,b2, ...bm, c1, -1. 

The third line would contain 
       c2, c3, ....ck, -1.
Output format :
The only line of output contains data of the first merged node. If there is no merging output should contain -1.

You don't have to explicitly print by yourself. It has been taken care of.
Constraints :
0 <= N <= 10^5
0 <= M <= 10^5
0 <= K <= 10^5.
-10^9 <= data <= 10^9 and data != -1


 Time Limit: 1 sec
CodingNinjas
author
2y
Brute Force
  • For each node in the first list, traverse the entire second list
  • Check if any node in the second list coincides with the first list
    • If it does, return that node’s data
    • If it doesn’t, return -1...read more
CodingNinjas
author
2y
Hashing Approach
  • Traverse the first list and store the address/reference to each node in a hash set/map/dictionary.
  • Then check every node in the second list:
    • If the address of the node of the second list...read more
CodingNinjas
author
2y
Parallel Traversal Approach
  • Calculate the length of both the lists, say len1 and len2
  • Get the absolute difference of the lengths, diff = |len1 – len2|
  • Now traverse the long list from the first node till ...read more
Add answer anonymously...
24/7 Customer Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter