AlgoTales · Roadmap

Intersection of lists

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Two chains can start separately and then join into one shared tail. Finding the intersection means finding the first item they have in common. A neat trick makes both walkers cover equal distances so they meet exactly there, without extra memory.

Practical use cases

  • Web app: Where two Git branches share history. A deployment tool wants to tell developers which commit their feature branch and main branch last had in common. Each branch is a chain of commits that eventually joins the same older history. Finding the first shared commit shows exactly what is new on each side.
  • Web app: Common ancestor of two categories. In an e-commerce catalogue, an admin wants to know the nearest category that both "Running shoes" and "Football boots" belong to. Following parent links up from each one until the paths meet gives "Sports footwear", which can then be used for a combined landing page.
  • System: Shared structure and route joining. Version control, file systems that share blocks, and route planners all have separate paths that merge into a common stretch. Finding where two paths join tells you what is shared and what is unique, which is how tools decide what really changed between two versions.

The story: Two Villages, One Highway

Two villages, Rampur and Shyamgaon, each have a dirt road leading to the same highway into the city. Rampur's road is short and Shyamgaon's is long, but after the point where they join, the road to the city is one and the same. A new bus company asked: "At which junction do the two roads meet?"

Drivers could not see from above, only follow their road. Mira's first idea: "Write down every junction of Rampur's road, then drive Shyamgaon's road and see which junction is already on the list." That works, but needs a long list of junctions (extra memory).

Kabir had a cleverer trick. "Two buses start at the same time, one from each village. When a bus reaches the end of the city road, it is teleported to the other village's start and continues. The two buses travel the same total distance: own road + shared road + other village's road. So they must arrive at the junction at the same moment."

And if the roads never joined? Both buses fall off the end at the very same moment, together, so you can say "no intersection". That is the intersection of two linked lists: find the node (by identity, not by value!) where two lists start to share nodes. It uses O(1) extra memory and O(n + m) time.

How to spot this problem, and where you need it

Two separate sequences follow links and eventually become the same sequence, and you want to find the first item where they merge, without comparing every item to every other one.

Signs you need it

  • The data is two chains or parent paths that share a common ending, such as branch histories or category ancestors.
  • The problem says "find the node where two linked lists intersect" or "lowest common point of two paths".
  • You are using two nested loops to compare every item of one path with every item of the other.

Where to use it in a project

  • Finding the merge base of two branches or versions of a document.
  • Finding a shared parent in category trees, org charts or folder paths.
  • Spotting where two request or data flows join into the same pipeline.

The solution

Put one walker at the start of each chain. Move both forward one step at a time. When a walker reaches the end of its own chain, send it to the start of the other chain. After this swap both walkers have travelled the same total distance, so they arrive at the shared item at the same moment. If there is no shared part, both end up empty together.

Payoff: Before: comparing each of 10,000 items against 10,000 others, about 100 million checks. After: at most 20,000 steps.

Explain it like I am 8

Two kids walk along two different paths that later join into one path. Each time a kid reaches the end, they run to the start of the other kid's path. Both kids end up walking the same total distance, so they arrive at the joining point at the same moment.

How it works, step by step

  1. Put pointer p at the head of A and pointer q at the head of B.
  2. Move both one step at a time.
  3. When p falls off the end of A (becomes null), restart it at the head of B. Do the same for q: end of B, restart at head of A.
  4. Stop when p === q. That is the intersection node.
  5. If they never share a node, both reach null at the same time, so the answer is null (no intersection).

The code in four languages

PHP

<?php
class Node {
    public $val;
    public ?Node $next = null;
    public function __construct($val, ?Node $next = null) { $this->val = $val; $this->next = $next; }
}

// returns the first shared node, or null if the lists never meet
function intersection(?Node $headA, ?Node $headB): ?Node {
    $p = $headA;
    $q = $headB;
    while ($p !== $q) {
        $p = ($p === null) ? $headB : $p->next;   // fell off A? go to B's head
        $q = ($q === null) ? $headA : $q->next;   // fell off B? go to A's head
    }
    return $p;       // same node, or both null when there is no intersection
}

// the shared tail c1 -> c2 -> c3
$c3 = new Node('c3');
$c2 = new Node('c2', $c3);
$c1 = new Node('c1', $c2);
$a = new Node('a1', new Node('a2', $c1));                 // list A: a1 a2 c1 c2 c3
$b = new Node('b1', new Node('b2', new Node('b3', $c1))); // list B: b1 b2 b3 c1 c2 c3

$hit = intersection($a, $b);
echo 'Lists meet at: ' . ($hit === null ? 'nowhere' : $hit->val) . "\n";   // c1

$x = new Node('x1', new Node('x2'));
$y = new Node('y1');
$none = intersection($x, $y);
echo 'Separate lists meet at: ' . ($none === null ? 'nowhere' : $none->val) . "\n";   // nowhere

JavaScript

class Node {
  constructor(val, next = null) { this.val = val; this.next = next; }
}

// returns the first shared node, or null if the lists never meet
function intersection(headA, headB) {
  let p = headA;
  let q = headB;
  while (p !== q) {
    p = (p === null) ? headB : p.next;   // fell off A? go to B's head
    q = (q === null) ? headA : q.next;   // fell off B? go to A's head
  }
  return p;      // same node, or both null when there is no intersection
}

// the shared tail c1 -> c2 -> c3
const c3 = new Node('c3');
const c2 = new Node('c2', c3);
const c1 = new Node('c1', c2);
const a = new Node('a1', new Node('a2', c1));                  // list A: a1 a2 c1 c2 c3
const b = new Node('b1', new Node('b2', new Node('b3', c1)));  // list B: b1 b2 b3 c1 c2 c3

const hit = intersection(a, b);
console.log('Lists meet at: ' + (hit === null ? 'nowhere' : hit.val));   // c1

const x = new Node('x1', new Node('x2'));
const y = new Node('y1');
const none = intersection(x, y);
console.log('Separate lists meet at: ' + (none === null ? 'nowhere' : none.val));   // nowhere

Java

public class Main {
    static class Node {
        String val;
        Node next;
        Node(String val, Node next) { this.val = val; this.next = next; }
        Node(String val) { this(val, null); }
    }

    // returns the first shared node, or null if the lists never meet
    static Node intersection(Node headA, Node headB) {
        Node p = headA;
        Node q = headB;
        while (p != q) {
            p = (p == null) ? headB : p.next;   // fell off A? go to B's head
            q = (q == null) ? headA : q.next;   // fell off B? go to A's head
        }
        return p;       // same node, or both null when there is no intersection
    }

    public static void main(String[] args) {
        // the shared tail c1 -> c2 -> c3
        Node c3 = new Node("c3");
        Node c2 = new Node("c2", c3);
        Node c1 = new Node("c1", c2);
        Node a = new Node("a1", new Node("a2", c1));                  // list A: a1 a2 c1 c2 c3
        Node b = new Node("b1", new Node("b2", new Node("b3", c1)));  // list B: b1 b2 b3 c1 c2 c3

        Node hit = intersection(a, b);
        System.out.println("Lists meet at: " + (hit == null ? "nowhere" : hit.val));   // c1

        Node x = new Node("x1", new Node("x2"));
        Node y = new Node("y1");
        Node none = intersection(x, y);
        System.out.println("Separate lists meet at: " + (none == null ? "nowhere" : none.val));   // nowhere
    }
}

Go

package main

import "fmt"

type Node struct {
	val  string
	next *Node
}

// intersection returns the first shared node, or nil if the lists never meet.
func intersection(headA, headB *Node) *Node {
	p, q := headA, headB
	for p != q {
		if p == nil { // fell off A? go to B's head
			p = headB
		} else {
			p = p.next
		}
		if q == nil { // fell off B? go to A's head
			q = headA
		} else {
			q = q.next
		}
	}
	return p // same node, or both nil when there is no intersection
}

func name(n *Node) string {
	if n == nil {
		return "nowhere"
	}
	return n.val
}

func main() {
	// the shared tail c1 -> c2 -> c3
	c3 := &Node{val: "c3"}
	c2 := &Node{val: "c2", next: c3}
	c1 := &Node{val: "c1", next: c2}
	a := &Node{"a1", &Node{"a2", c1}}              // list A: a1 a2 c1 c2 c3
	b := &Node{"b1", &Node{"b2", &Node{"b3", c1}}} // list B: b1 b2 b3 c1 c2 c3

	fmt.Println("Lists meet at:", name(intersection(a, b))) // c1

	x := &Node{"x1", &Node{val: "x2"}}
	y := &Node{val: "y1"}
	fmt.Println("Separate lists meet at:", name(intersection(x, y))) // nowhere
}

Time: O(n + m) · Extra space: O(1). Each walker covers at most both lists once; only two pointers are used.

Watch out for

  • Comparing node values: two different nodes can hold equal values. Intersection means the same node object.
  • Moving to the other head when p.next is null instead of when p is null. The null step is what keeps both walkers in step, and what stops the loop when there is no intersection.
  • Assuming the lists have the same length; the switch trick exists precisely because they usually do not.

Quick check

  1. What counts as an intersection?
    • Two nodes with equal values
    • Two lists of the same length
    • The same node object reachable from both lists
    • Two lists that are both sorted
  2. Why do the two walkers arrive together at the shared node?
    • Both walk the same total distance (own part + other part + shared part)
    • The longer list is shortened first
    • One of them waits
    • They run at different speeds
  3. What do p and q equal when the lists never intersect?
    • The two heads
    • The last real nodes
    • The middle nodes
    • Both are null at the same time