DSA and coding Level 1 This level · 10 of 19
Easy dsa linked-lists

Intersection of Two Linked Lists

The 30 second answer

The two lists may share a common tail. I walk one pointer down each list, and when a pointer reaches the end I send it to the head of the other list. They travel the same total length and therefore meet at the first shared node, or both land on null if the lists do not intersect.

Could you say this in an interview?

Problem Given the heads of two singly linked lists, return the node at which they intersect, or null if they do not share a tail. The intersection is by node reference, not by value. Original: LeetCode 160: Intersection of Two Linked Lists. HackerRank Find Merge Point of Two Lists is the same idea.

Understanding the prompt The lists may have different prefixes. After the merge point they are the same chain, so you must return that node object, not a new node with the same value. There is no cycle.

Pattern recognition Fast and slow pointers in the broader family of two-pointer list walks; here the two pointers simply switch heads so their remaining distances become equal.

Brute force Store every node of list A in a HashSet, then walk B until you hit a node in the set: O(n + m) time and O(n) space. Measuring both lengths and advancing the longer list first is O(1) extra space and two passes.

Optimal p starts at A, q at B. While they are not the same reference, each pointer moves to next, or to the other list's head when it falls off the end. If there is an intersection they meet there; if not they both become null at the same time and the loop ends. No length pre-pass is required.

Alternatives The length-difference version is easier to prove on a whiteboard if the switch-heads trick feels too cute. Both are linear time and constant space.

Java solution

public class IntersectionOfTwoLinkedLists {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    static ListNode list(int... a) {
        var dummy = new ListNode(0);
        var t = dummy;
        for (int x : a) {
            t.next = new ListNode(x);
            t = t.next;
        }
        return dummy.next;
    }

    static String str(ListNode h) {
        var sb = new StringBuilder("[");
        for (ListNode p = h; p != null; p = p.next) {
            if (sb.length() > 1) sb.append(", ");
            sb.append(p.val);
        }
        return sb.append("]").toString();
    }

    static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode p = headA, q = headB;
        while (p != q) {
            p = p == null ? headB : p.next;
            q = q == null ? headA : q.next;
        }
        return p;
    }

    public static void main(String[] args) {
        var common = list(8, 4, 5);
        var a = new ListNode(4, new ListNode(1, common));
        var b = new ListNode(5, new ListNode(6, new ListNode(1, common)));
        System.out.println(getIntersectionNode(a, b).val); // 8
        var c = list(2, 6, 4);
        var d = list(1, 5);
        System.out.println(getIntersectionNode(c, d) == null); // true
    }
}

Complexity O(n + m) time, O(1) extra space.

Edge cases

  • Official-style sample: A is 4 -> 1 -> 8 -> 4 -> 5 and B is 5 -> 6 -> 1 -> 8 -> 4 -> 5, sharing the node 8, returns 8.
  • No intersection: the pointers both end at null.
  • One list is a suffix of the other: they meet at the shorter list's head.

Follow-ups

  • HackerRank Find Merge Point of Two Lists asks for the value at the merge node, which is the same walk.
  • If the lists could have cycles, you must first find and handle the cycle starts.

Tests Lists that share a tail starting at 8 return that node. Two disjoint lists 2,6,4 and 1,5 return null.

How to say it in the interview "I walk one pointer down each list and, when a pointer runs out, I send it to the head of the other list. They then travel the same total distance and meet at the first shared node, or both become null if the lists do not intersect. Linear time, constant space."

Sources (2)
  1. LeetCode 160: Intersection of Two Linked Listsleetcode.com
  2. HackerRank: Find the Merge Point of Two Joined Linked Listshackerrank.com
Previous
Next