← Back to Visualizer Gallery
Traversal · Word Ladders & Bidirectional BFS LeetCode 127

Word Ladder / bidirectional BFS & frontier swapping

Transforming words one letter at a time: replace $O(N^2)$ pairwise checks with $O(26 \cdot L)$ neighbor generation. Expand simultaneously from start and target, swapping frontiers to always expand the smaller set.

Execution Stage

idle
INVARIANT Bidirectional BFS Invariant: Always expand the smaller frontier: if (beginSet.size() > endSet.size()) swap(beginSet, endSet). This trims the branching volume from $O(b^d)$ down to $O(2 \cdot b^{d/2})$.
Ladder Length 1
Forward Frontier 0
Backward Frontier 0
Forward Set 0 words
Backward Set 0 words
Press Run to trace bidirectional BFS.
0 / 0
Speed

Java · Reference Algorithm

INTERVIEW SCRIPT

How to Present Word Ladder to an Interviewer

1. Neighbor Generation vs Pairwise

"Pairwise string comparison takes $O(N^2 \cdot L)$ time. Instead, for word of length $L$, mutate each character $26$ times and check membership in wordSet in $O(26 \cdot L)$ time."

2. Bidirectional BFS Concept

"Standard BFS explodes with exponential branching $b^d$. Searching from both beginWord and endWord meets in the middle at depth $d/2$, reducing states searched to $2 \cdot b^{d/2}$."

3. The Frontier Swapping Invariant

"At each layer, we inspect beginSet.size() > endSet.size(). Swapping to always expand the smaller set ensures we minimize immediate branching."

4. Collision Termination

"The moment a neighbor generated from beginSet is found in endSet, the two frontiers have touched: return length + 1 immediately."

Word Ladder (LC 127) — Bidirectional BFS · Time $O(N \cdot 26 \cdot L)$, Space $O(N \cdot L)$.