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, headA and headB, return the node where the two lists join, or null if they never join. Two lists join when, from some node on, they share the very same nodes, not just nodes with equal values. Neither list has a cycle, and both must keep their structure.

Example 1
Input: listA = [4, 1, 8, 4, 5], listB = [5, 6, 1, 8, 4, 5], shared from the node with value 8
Output: the node with value 8
Explanation: the two 1s have the same value but are different nodes.
Example 2
Input: listA = [2, 6, 4], listB = [1, 5], no shared nodes
Output: null
Solution

The Idea

A linked list is a chain of nodes. Each node holds a value and a link, called next, to the node after it, and the last node's next is null. "Singly" means the links only go forward. Two such chains can run into each other, the way two roads merge: after the merge point there is only one road.

Look at the top half of the picture below. List A starts at headA with 4 and 1, and list B starts at headB with 5, 6 and 1. The next of A's 1 and the next of B's 1 point to the same node 8. From there on the two lists are one chain, the shared part 8, 4, 5, and that node 8 is the answer.

List A is 4, 1 and list B is 5, 6, 1, and both continue into the same shared part 8, 4, 5. Below, pointer a walks 4, 1, 8, 4, 5, null, then 5, 6, 1, 8, and pointer b walks 5, 6, 1, 8, 4, 5, null, then 4, 1, 8. Both reach the shared 8 on move 9.

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 ==, which in Java checks whether two references point at the same object, and never compare values.

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 a and pointer b. Pointer a walks all of list A, steps onto the null at its end, and then starts again at headB. Pointer b does the same the other way round: all of list B, null, then headA. Move 0 is where each pointer starts.

Count the moves until each pointer reaches 8 a second time. Pointer a passes A's 2 own nodes, the 3 shared nodes, the null and B's 3 own nodes: 9 moves. Pointer b passes B's 3 own nodes, the 3 shared ones, the null and A's 2 own nodes: also 9. Both add up the same pieces in a different order, so they land on the shared 8 together, on move 9.

And if nothing is shared? Then both pointers walk both lists to the end and step onto the null after their second list on the same move. Two null references are equal too, so the walk stops there, and null is the answer.

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, then walk B and return the first node already in the set. That takes one pass over each list, but the set holds all m nodes of A, so the memory grows with the list. The two-pointer walk needs only two variables.

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 a reaches the first shared node for the second time after x + z + 1 + y moves, and pointer b after y + z + 1 + x moves. The sums are equal, so the two pointers always arrive together. In example 1, x = 2, y = 3 and z = 3, which gives the 9 moves in the picture.

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 null? On null. That extra move is the "+ 1" in both sums above, so the distances stay equal. More importantly, it gives the walk an end when the lists share nothing. With m nodes in A and n in B, each pointer reaches the null after its second list on move m + n + 1, and the loop stops.

Java Solution

The method getIntersectionNode works in these steps:

  1. First, start two pointers: a at headA and b at headB.
  2. Loop while a != b, that is, while the two pointers stand on different nodes (or one of them is null and the other is not).
  3. In each move, a takes one step: if it is null, it jumps to headB, otherwise it moves to a.next. Pointer b does the same, jumping to headA.
  4. When the loop stops, a and b are the same, so return a: the shared node, or null when nothing is shared.

Around the method sit a small ListNode class and a few helpers: build makes a list from values, join links the last node of one list to another list, and run prints both lists and the answer's index in each list, counting from 0.

The main method runs both examples, two lists with the same number of nodes before the shared part, a list that is the whole tail of the other, the same list passed twice, and an empty list A.

Java
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:

Output
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] and [1, 5] share nothing, and both pointers become null together on move 6, which is 3 + 2 + 1.

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] is the end of B, so the answer is headA itself, at index 0 in A and index 2 in B.

The fifth line passes the same list twice. Then a == b before the first move, the loop never runs, and the head comes back. On the last line, list A is empty, so a starts as null and jumps to headB on its first move. Both pointers are null on move 3, and the answer is null.

The jump on null matters. A version that jumps when a.next == null, on the last node, never steps onto null, so the two pointers are never both null. On example 2 it was still looping after 1,000 moves, when a test cap stopped it.

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 null and the other list, so the loop makes at most m + n + 1 moves.
  • Space: O(1). Only the two pointers a and b are stored. No set of visited nodes is kept, and the lists are not changed.