Yahoo Interview Question
Software Engineer / DevelopersIf there is a common code, then it shd look like a 'Y'. So first go thru both linked list to find their lengths in O(n). Get the difference between length, say d.
say, head1 and head2 are pointers to linkedlists
scan thru the list :
compare head1->value == (head2+d)->value
total is O(n) time
I like the idea with the stacks. :) But you can make it for O(n) memory I believe:
bool CommonNode(List* aList, List* bList)
{
List* a = aList, *b = bList;
while( (a != NULL) && (b != null) )
{
if(a == b)
return true;
a = a->pNext;
b = b->pNext;
}
return false;
}
A valid improvement of the algorithm will be if you make step equal to a = a->pNext->pNext. Or even more, but this requires more chechs to not going read from null.
Think this will work only if the common node is at the same distance from both the heads.
Please correct me if I am wrong.
All we need to do is to first calculate len=len1-len2 (len1>len2, as discussed above). Point p1 and p2 to list1 (the longer one) and list2 respectively. Then step only p1 for "len" no. of nodes. After this we are guaranteed that p1 and p2 are equidistant from the common node. So now start stepping p1 and p2 simultaneously until p1==p2. This will the common node. This is a simple O(n) solution.
use recursive we can make it with o(n) time, only one transverse needed.
int commomNode(list* p1, listp2) {
if (p1 == NULL && p2 == NULL)
return 0;
else if (p1 == NULL)
return commomNode(p1,p2->next);
else if (p2 == NULL)
return comonNode(p1->next,p2);
else
return commonNode(p1->next,p2->next);
if (p1 == p2)
return 1;
else
return 0;
}
}
the algorithm of finding differences in lengths will not work since the first node itself can be the common node.
The answer given by Anonymous on December 26, 2008 is correct.
Just one flaw, what if the linked list is a circular list. The algorithm fails
eg First Linked List A->B->C->D->C
Second Linked List Z->Y->C->D->C
To solve this have another data member in each node. Set the data member to 1 when we visit for the first time during First Linked List traversal.
When we traverse the second linked list, check if any node has the data member set to 1.
- Push all the nodes into 2 different stacks.
- onion834 September 04, 2008- Then pop once from both stacks to check if the nodes are same,
- - if so continue popping till the nodes differ.
- - else there are no common nodes