Suppose there are two singly linked lists both of which intersect at some point and become a single linked list.
The head or start pointers of both the lists are kno
Dump the contents (or address) of both lists into one hash table. first collision is your intersection.
Maybe irrelevant at this point, but here's my dirty recursive approach.
This takes O(M)
time and O(M)
space, where M >= N
for list_M
of length M
and list_N
of length N
2
. Note that list_N
will hit null
before list_M
, for M > N
M=N
intersects when list_M != list_N && list_M.next == list_N.next
M>N
intersects when list_N != null
Code Example:
Node yListsHelper(Node n1, Node n2, Node result) {
if (n1 == null && n2 == null)
return null;
yLists(n1 == null ? n1 : n1.next, n2 == null ? n2 : n2.next, result);
if (n1 != null && n2 != null) {
if (n2.next == null) { // n1 > n2
result.next = n1;
} else if (n1.next == null) { // n1 < n2
result.next = n2;
} else if (n1 != n2 && n1.next == n2.next) { // n1 = n2
result.next = n1.next; // or n2.next
}
}
return result.next;
}
This takes O(M+N) time and O(1) space, where M and N are the total length of the linked lists. Maybe inefficient if the common part is very long (i.e. M,N >> m,n)
Edit: See more here.
If possible, you could add a 'color' field or similar to the nodes. Iterate over one of the lists, coloring the nodes as you go. Then iterate over the second list. As soon as you reach a node that is already colored, you have found the intersection.
This is crazy solution I found while coding late at night, it is 2x slower than accepted answer but uses a nice arithmetic hack:
public ListNode findIntersection(ListNode a, ListNode b) {
if (a == null || b == null)
return null;
int A = a.count();
int B = b.count();
ListNode reversedB = b.reverse();
// L = a elements + 1 c element + b elements
int L = a.count();
// restore b
reversedB.reverse();
// A = a + c
// B = b + c
// L = a + b + 1
int cIndex = ((A+B) - (L-1)) / 2;
return a.atIndex(A - cIndex);
}
We split lists at three parts: a
this is part of the first list until start of the common part, b
this is part of the second list until common part and c
which is common part of two lists. We count list sizes then reverse list b
, this will cause that when we start traversing list from a
end we will end at reversedB
(we will go a -> firstElementOfC -> reversedB
). This will give us three equations that allow us to get length of common part c
.
This is too slow for programming competitions or use in production, but I think this approach is interesting.
Check last nodes of each list, If there is an intersection their last node will be same.