LeetCode 160 · Linked list

Intersection of Two Linked Lists, explained with a picture

Two branch lines joining one track.

Linked list
▶ Watch it step by step

The problem

Two linked lists merge at some node and share the rest. Find that first shared node (or none).

Input:  A = 4 → 1 → [8 → 4 → 5], B = 5 → 6 → 1 → [8 → 4 → 5]
Output: the node 8

Picture it

Picture two branch lines joining one shared track. One walker on each branch. When a walker reaches the end, they jump to the start of the other branch. Both walk the same total distance (A + B), so they arrive at the junction at the same moment.

Short version: the full lesson (brute force, complexity, edge cases and a quiz) is still being written. The animation is complete.

The key idea

Switch heads at the end; the pointers meet at the intersection or both reach None. O(m + n), O(1).

Python solution

def get_intersection(a, b):
    pa, pb = a, b
    while pa is not pb:
        pa = pa.next if pa else b
        pb = pb.next if pb else a
    return pa

In the interactive version each line lights up as the animation runs, and you can type your own input to see the algorithm handle it.