30 Day Risk-Free Guarantee:
100% money back if you're unsatisfied.
Book (308 Pages):
  • 150 Programming Interview Questions and Solutions
  • Five Proven Approaches to Solving Tough Algorithm Questions
  • Ten Mistakes Candidates Make -- And How to Avoid Them
  • Steps to Prepare for Behavioral and Technical Questions
  • Interview War Stories: A View from the Interviewer's Side
  • Book Preview and More Info

Video (One Hour):
  • Watch CareerCup's founder perform a totally unscripted technical interview of a candidate.
  • Overview of what interviewers look for in software engineering jobs.
  • Technical questions with white-boarding coding where the candidate does well - and struggles.
  • Interviewer reviews with what went well and poorly.
  • Video Preview and More Info

Resume Review (24 - 48hr)
  • Get your resume reviewed by a trained engineering interviewer. More Info
All Products / Services


Express Prep Package (Book)
$29.99 for e-book | $32.45 for paperback
Buy E-Book Buy on Amazon


Standard Prep Package (E-Book & Video)
Emailed Instantly | $39.99
Buy Standard

Elite Prep Package (E-Book, Video & Resume)
Emailed Instantly | $99.99
Buy Elite
 



There are two linked lists which converge at one point. Return the 1st node at which they converge

[__]-->[__]-->[__]-->
[__]-->[__]
[__]-->

Hope my diagram is understandable

37


Anonymous on February 08, 2009 |Edit | Edit

Using the head of 2nd LL, get the addr of first node. Then while traversing the 1st compare every nodes addr. If math found break

Also do the vice versa process

this is n square. on February 10, 2009 |Edit | Edit

this is n square.

Anonymous on February 12, 2009 |Edit | Edit

traverse L1, put each node address in an array A[1..n];
traverse L2, put each node address in another array B[1..m];
compare A[n-i] with B[m-i] (i=0..n or m), find where A[n-j]!=B[m-j]
if j==0, no merge
if j>0, merge at node address A[n-j+1]
O(m+n)

Anon on February 12, 2009 |Edit | Edit

good one...anyone?
remember that the nodes of 2 LLs before the convergeence point neednt be the same...

Anonymous on February 12, 2009 |Edit | Edit

well i posted this question

1 answer that i came across is

take 1 node at a time in 1st list. for each node traverse all nodes of 2nd list and compare.
if the two nodes converge there will be a match at some time, that is the node you need to return

mohit on September 02, 2009 |Edit | Edit

it is not written in question, you can't have matching before merging point. better solution is find no of elements of both list say n1 & n2, take difference of two. traverse the bigger array first up to difference got & then traverse both list simultaneously & break wherever you are getting same address.

morpheus on February 12, 2009 |Edit | Edit

I guess above solution is descent one.

else,
put the addresses of each node of LL1 in a hashtable.
when trying to put addresses of nodes of LL2 in the same hashtable, if there is collission, check if the same address exists, if yes that node is the point of convergence.

bluetide on February 13, 2009 |Edit | Edit

How about push these nodes into two stacks, after reaching the end, start to pop them. When the two top nodes are different, the one that just being popped out is the convergence node.

coder_hello on February 13, 2009 |Edit | Edit

we could have 2 pointers.

curr1 pointing to the head node of the first list say head1 and similarly curr2 pointing to the head node of the second list.I wrote the following pseudo code,i guess this should work.

curr2=head2;
while(curr2!=NULL)
{
curr1=head1;
while(curr1!=Null)
{
if(curr1==curr2)
return curr1;
else
curr1=curr1->next;
}
curr2=curr2->next;
}
This way we ensure that each and every node in list 2 would be compared with every other node in list one the moment a match ..i.e convergence point is found the node would be returned.

Shah on April 30, 2009 |Edit | Edit

Its simple, I think it shoudl work.

prabagaran on August 10, 2009 |Edit | Edit

It takes O(n*n) time complexity.
Give a solution in O(n)

Anonymous on February 16, 2009 |Edit | Edit

What if 2 list split after merge?
This case should also be considered?

Anonymous on February 23, 2009 |Edit | Edit

Cmon Dude..! Its a singly Linked List

Anonymous on February 16, 2009 |Edit | Edit

will the above solution work for these two lists?

1 2 3 4 5 6 7 8 9

1 2 5 4 6 6 7 8 9

Anonymous on February 17, 2009 |Edit | Edit

1) calculate the lengths of the two list, take n+m time.

2) assume n>=m, let the current elements of list1 and list2 are the heads, and then list 1 go to the (n-m)th element,

3) compare the current element , if matched, return current element, else let the current elements of two list be the next.

4) if ended, return null;

addy on August 15, 2009 |Edit | Edit

Good solution.

Anonymous on February 17, 2009 |Edit | Edit

how will they split after merging as the common node will be able to point to just one node...So after merging they will have common list..

Anonymous on February 17, 2009 |Edit | Edit

->Take hash of all the addresses of L1

-> Start off with taking hash of address of each node in L2. If collision occurs compare the address. If addresses matches you get the common node.

-> Hashing function for L1 must be collision free for L1.

Ramsundar on March 05, 2009 |Edit | Edit

compare the sizes of both; - o(n)
take difference of them, say it k - o(1)
find the bigger list - o(1)
move the bigger list k times - o(n)
now move both the smaller and larger list one at a time -o(n)
For each comparison check whther they point to the same address -o(1)
if yes return the node and exit the function -

Total time complexity - o(n)

coder_hello on March 11, 2009 |Edit | Edit

To Anonymous on February 16, 2009
will the above solution work for these two lists?

1 2 3 4 5 6 7 8 9

1 2 5 4 6 6 7 8 9

Here we are dealing with address locations so if if the two lists point to the same address where 1 is stored then there itself you would get the point of convergence.It would not move any further.However this could be considered as atest case and surround some peice of code to endsure that if the lists are typically the same then eithere they r one and the same list or say point of covergence is first node or throw some error message.

savior on April 05, 2009 |Edit | Edit

Reverse both the lists and traverse the lists simultaneously till they diverge.
Reversing should take O(m+n) and then traversing the lists should take O(m) or O(n) depending on which is smaller.

One downside of this solution is that the lists are reversed. If the original lists have to be preserved, we might have to reverse the lists again.

anon on April 18, 2009 |Edit | Edit

above solution wouldn't work since the moment 1 list is reversed the common node between other list and this list would be lost.

best way would be Ramsundar's .. in O(n) time

KD on May 12, 2009 |Edit | Edit

Node *listMergeNode(Node *head1,Node *head2)
{
if(!head1 || !head2) return NULL;
Node *list1 = head1;
Node *list2 = head2;

if(!list1->next || !list2->next) return NULL;

while(list1 && list2)
{
}
}

KD on May 12, 2009 |Edit | Edit

Node *listMergeNode(Node *head1,Node *head2)
{
if(!head1 || !head2) return NULL;
Node *list1 = head1;
Node *list2 = head2;

while(*list1 && *list2)
{
if(*list1 == *list2)
return list1; //we have found the merge

list1 = list1->next;
list2 = list2->next;
}
return NULL; // if we reach here we have reached end of 1 of the list and no elem was found
}

Kang on May 13, 2009 |Edit | Edit


Node findCommon(Node h1, Node h2) {
Stack s = new Stack();
s.push(h1);
while(h1 != null && h2!=null) {
Node n = s.pop();
if(n == h2) {
return n;
} else {
s.push(n);
h1 = h1.next();
s.push(h1);
h2 = h2.next();
}
}
return null;

Anonymous on June 29, 2009 |Edit | Edit

Following algo is m+n with no extra space.

If lists are allowed to be altered do the following -

1. Recursively reverse list 1
2. Transverse list 2. When you find a node with next pointer pointing at the node the node itself then you have the first node where the lists converge

kaushal on July 20, 2009 |Edit | Edit

find the length of both linklist l1 and l2. then take one extra variable X=l1-l2. after it traverse l1 increment by x. untill not found l1==l2

mg on August 03, 2009 |Edit | Edit

If you consider the tail of the lists as a root of a tree, and the heads as leaves, this is finding the first common ancestor of the given two leaves.

mg on August 03, 2009 |Edit | Edit

Edit: If you consider the tail of the lists as a root of a tree where nodes have pointers to their parents, and the heads as leaves, this is finding the first common ancestor of the given two leaves. You should start at the leaves, calculate the depth of each (n and m) then pick the longer and traverse up abs(n - m), now we are looking at them at the same level, then traverse up level by level checking on the parent of each until they are the same or NULL.

Addy on August 15, 2009 |Edit | Edit

you have got the correct idea. well explained !!

mayank on August 18, 2009 |Edit | Edit

use one visit tag with each node like "TRAVERSED" and make it true or false accordingly in case we've to form it from initial.....traversal should be independent ....howz it?

LLOLer on August 19, 2009 |Edit | Edit

the smartest answer was from bluetide...rest are just duplication of previous solutions...

dumb ass on September 28, 2009 |Edit | Edit

mohit's solution is the real workable solution and bluetide is also good one

Anonymous on January 03, 2010 |Edit | Edit

If we are not allowed to use any extra data structure, e.g, stack or hashtable, I guess the solution would be:
assume the common node is k th node counting from the tail, then, it is n-k + 1 and m-k+1 node counting from the head. Therefore, first reverse the first link link and point the head of the first link link (now the tail) to the head of the second link link. Starting count from the head of the second link link to see how many nodes it traverse to reach itself (as there is a loop), which should be n+m-2k+1. Hence, if we count n and m at the begining, we could compute k and starting from the tail, we can identify this command node.

divyaC on April 23, 2010 |Edit | Edit

1. get l1=length of L1
2. get l2= length of L2
3. diff=abs(l1-l2)
4. traverse the longer list for diff times.
5. from this point both the lists will have same number of elements.
6.traverse both the lists simultaneously comparing its curr->next, return when these addresses match..

7.O(2m+2n), where m and n are lengths of lists

rohin on August 13, 2010 |Edit | Edit

1. traverse list1 till end and count elements (n1) (store last node ptr)
2. traverse list2 till end and count elements (n2)
3. compare last node of two lists it should be same. else no intersection
now let the common part of two lists have k nodes then
n1= number of different nodes of list1 (pre_n1) + k
n2= number of different nodes of list2 (pre_n2) + k
n1-n2 = prev_n1 - pre_n2
by traversing the smaller list by |prev_n1-prev_n2| i.e |n1-n2| nodes we will arrive at point of intersection.
complexity
o(n1)+o(n2)+o(|n1-n2|) ~ o(n)

Add a Text Comment | Add Runnable Code
Name:
Comment:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.








Amazon (1033)Bloomberg LP (403)Qualcomm (117)Adobe (88)Goldman Sachs (78)NetApp (49)IBM (43)Morgan Stanley (33)CapitalIQ (30)Sophos (25)Achieve Internet (23)Electronic Arts (19)Motorola (18)Research In Motion (17)Flipkart (16)
Microsoft (867)Google (141)NVIDIA (98)Yahoo (82)Epic Systems (69)Expedia (47)VMWare Inc (43)Apple (32)Cisco Systems (28)Facebook (23)Infosys (22)Agilent Technologies (19)Sage Software (17)Deshaw Inc (16)FlexTrade (15)
More Companies »
Software Engineer / Dev... (1062)Financial Software Deve... (170)Testing / Quality Assur... (56)Analyst (35)Virus Researcher (25)Field Sales (15)Developer Program Engin... (9)Front-end Software Engi... (6)MyJoB (5)area sales manager (4)Assistant (3)Cabin crew (2)Accountant (1)personnel (1)Intern (1)
Software Engineer in Te... (288)Program Manager (65)Development Support Eng... (47)INTERN(MSIDC) (28)Web Developer (18)System Administrator (10)Consultant (10)Production Engineer (5)Associate Technology L2 (5)AcquireKnowledge (4)Product Security Engine... (3)Solutions Architect (2)Gamer (1)mts (1)Fresh graduate interview (0)
More Job Titles »
Algorithm (1073)Terminology & Trivia (294)C (166)Object Oriented Design (159)Java (121)Testing (114)Arrays (101)Operating System (78)Database (70)Linked List (62)String Manipulation (56)Networking / Web / Inte... (44)Threads (36)Linux Kernel (33)PHP (22)
Coding (511)C++ (204)Behavioral (159)Data Structures (155)Experience (116)Brain Teasers (111)Computer Architecture &... (79)General Questions and C... (73)Trees and Graphs (69)Math & Computation (57)Application / UI Design (45)Ideas (38)System Design (35)Puzzles (30)Bit Manipulation (20)
More Topics »
CareerCup Official Interview Book Daily Questions Requests for Help Mock Interviews Video for Cracking the Coding Interview Job Placement Service CareerCup Blog
My Profile Edit Profile & Email Settings Sign Out