Sunday, June 2, 2013

Intersection of two linked lists

Problem:
There are two linked lists that intersect. Given two pointers to the heads of the lists, find the intersection point.

Solution:
Determine the length of each list - let it be L1 and L2. Traverse |L1 - L2| nodes in the longest list. Now both lists contain equal number of nodes before the intersection point. Simply traverse both lists with two pointers. Once the pointers point to the same node the intersection is found.

Difference in size approach


Complexity:
time - O(n)
space - O(1)
Links and credits:
http://www.kodelog.com/spot-the-intersection-of-linked-list/


No comments:

Post a Comment