Intersection of Two Linked Lists
Find the node where two linked lists join, or null if they never do.
Given the heads of two singly linked lists, headAheadBnull
Example 1
Output: the node with value 8
Explanation: the two 1s have the same value but are different nodes.
Example 2
Output: null
The Idea
A linked list is a chain of nodes. Each node holds a value and a link, called nextnextnull
Look at the top half of the picture below. List A starts at headAheadBnextnext
Notice the two 1s. They have the same value, but they are two separate nodes, one in each list. Joining is about the nodes themselves, so we compare nodes with ==
So how do we find node 8? If both lists had the same number of nodes before the shared part, we could walk them side by side, one node per move, and stop as soon as both walkers stand on the same node. Here A has two nodes before the shared part and B has three, so B's walker would always be one node behind. We cannot simply skip ahead, because we do not know where the shared part starts. That is the very thing we are looking for.
The way out is to give both walkers the same distance. Look at the bottom half of the picture, where the walkers are two variables, pointer abanullheadBbnullheadA
Count the moves until each pointer reaches 8 a second time. Pointer anullbnull
And if nothing is shared? Then both pointers walk both lists to the end and step onto the nullnullnull
Solution Approach
Turning that idea into code means looking at the simple way first, and then settling two things: why switching lists always evens out the distances, and when exactly a pointer switches.
The simple way with a set
Is there a more direct way? Say list A has m nodes and list B has n. Comparing every node of B with every node of A finds the answer, but takes up to m × n comparisons. Faster is to walk A once and put every node into a HashSet
Evening out the distances
Does switching lists work for any two lists, not only for this example? Call the number of nodes before the shared part x in list A and y in list B, and the length of the shared part z. Pointer ab
When x and y are equal, the pointers do not even need to switch: they reach the first shared node on move x, still in their own lists. Another way to even out the distances is to count both lists first and then start the pointer on the longer list further ahead by the difference. That works too, but needs an extra pass just for counting. Switching lists gets the same effect with no counting at all.
Switching lists at null
When should a pointer jump to the other list: on the last node, or one move later, on nullnullnull
Java Solution
The method getIntersectionNode
- First, start two pointers:
ata andheadA atb .headB - Loop while
, that is, while the two pointers stand on different nodes (or one of them isa != b and the other is not).null - In each move,
takes one step: if it isa , it jumps tonull , otherwise it moves toheadB . Pointera.next does the same, jumping tob .headA - When the loop stops,
anda are the same, so returnb : the shared node, ora when nothing is shared.null
Around the method sit a small ListNodebuildjoinrun
The main
public class IntersectionOfTwoLinkedLists {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA;
ListNode b = headB;
while (a != b) {
a = (a == null) ? headB : a.next; // after the end of A, walk B
b = (b == null) ? headA : b.next; // after the end of B, walk A
}
return a; // the shared node, or null when both reach the end together
}
static ListNode build(int... values) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (int v : values) {
tail.next = new ListNode(v);
tail = tail.next;
}
return dummy.next;
}
static ListNode join(ListNode front, ListNode rest) { // front's last node points to rest
if (front == null) {
return rest;
}
ListNode last = front;
while (last.next != null) {
last = last.next;
}
last.next = rest;
return front;
}
static String show(ListNode node) {
StringBuilder sb = new StringBuilder("[");
for (; node != null; node = node.next) {
sb.append(node.val).append(node.next != null ? ", " : "");
}
return sb.append("]").toString();
}
static int indexOf(ListNode head, ListNode target) {
int i = 0;
for (ListNode n = head; n != target; n = n.next) {
i++;
}
return i;
}
static void run(ListNode headA, ListNode headB) {
ListNode node = getIntersectionNode(headA, headB);
String answer = (node == null) ? "null" : "node " + node.val + " (index "
+ indexOf(headA, node) + " in A, index " + indexOf(headB, node) + " in B)";
System.out.println("A = " + show(headA) + ", B = " + show(headB) + " -> " + answer);
}
public static void main(String[] args) {
ListNode shared = build(8, 4, 5);
run(join(build(4, 1), shared), join(build(5, 6, 1), shared));
run(build(2, 6, 4), build(1, 5));
ListNode tail = build(2);
run(join(build(7, 9), tail), join(build(3, 6), tail));
ListNode inside = build(3, 4);
run(inside, join(build(1, 2), inside));
ListNode same = build(1, 2, 3);
run(same, same);
run(null, build(1, 2));
}
}
Running it prints:
A = [4, 1, 8, 4, 5], B = [5, 6, 1, 8, 4, 5] -> node 8 (index 2 in A, index 3 in B)
A = [2, 6, 4], B = [1, 5] -> null
A = [7, 9, 2], B = [3, 6, 2] -> node 2 (index 2 in A, index 2 in B)
A = [3, 4], B = [1, 2, 3, 4] -> node 3 (index 0 in A, index 2 in B)
A = [1, 2, 3], B = [1, 2, 3] -> node 1 (index 0 in A, index 0 in B)
A = [], B = [1, 2] -> null
Look at the first line: the answer is node 8, at index 2 in A and index 3 in B. It is not either of the 1s, which share a value but sit at index 1 in A and index 2 in B as separate nodes. On the second line, [2, 6, 4][1, 5]null
The third line shows lists that share only their last node, 2, with two nodes before it in each list. The pointers stand on 2 together on move 2, before either one switches lists. On the fourth line, all of [3, 4]headA
The fifth line passes the same list twice. Then a == banullheadBnullnull
The jump on nulla.next == nullnullnull
Complexity
All the work is the walk of the two pointers, one node each per move, and the walk is over by the time both have covered both lists.
- Time: O(m + n), with m nodes in list A and n in list B. Each pointer walks its own list, one
and the other list, so the loop makes at most m + n + 1 moves.null - Space: O(1). Only the two pointers
anda are stored. No set of visited nodes is kept, and the lists are not changed.b