Word Ladder

HardBFS · Implicit Graph🧩 Graph BFSLeetCode #127 ↗Updated

Problem

Turn beginWord into endWord changing one letter per step; every word after the first must be in wordList. Return the word count of the shortest such chain (both ends included), or 0 if none.
Inputhit → cog, [hot,dot,dog,lot,log,cog]Output5
Inputhit → cog, [hot,dot,dog,lot,log]Output0

word length M ≤ 10  ·  N = |wordList| ≤ 5000  ·  lowercase, unique  ·  begin ≠ end

Try it yourself

Java
class Solution {
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Words are nodes, one-letter changes are edges of an unweighted graph ⇒ BFS. Generate neighbours by trying 26 letters per position, not by scanning the list.
PatternGraph BFS

Instinct Minimum moves, fewest steps or shortest transformation where every step costs the same: spread outward level by level with a queue.

Memory hack Ripples in a pond: every ring is one step farther, so the first ring that touches the target is the answer.

Open the Graph BFS guide →

Approaches

Brute ForceBFS, Compare with Every Word

Time O(N2·M)Space O(N)

Plain level-order BFS; neighbours are found by scanning the whole list for unused words differing in exactly one position — O(N·M) per dequeued word.

Java
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
    boolean[] used = new boolean[wordList.size()];
    Queue<String> queue = new LinkedList<>(List.of(beginWord));
    for (int level = 1; !queue.isEmpty(); level++) {
        for (int size = queue.size(); size > 0; size--) {
            String cur = queue.poll();
            if (cur.equals(endWord)) return level;
            for (int i = 0; i < wordList.size(); i++) {
                String w = wordList.get(i);
                int diff = 0;
                for (int k = 0; k < w.length(); k++) if (w.charAt(k) != cur.charAt(k)) diff++;
                if (!used[i] && diff == 1) { used[i] = true; queue.offer(w); }
            }
        }
    }
    return 0;
}

Correct shortest path, but the neighbour scan is quadratic in N.

At a glance

LevelApproachTimeSpace
Brute ForceBFS, Compare with Every WordO(N2·M)O(N)
BetterBFS with Letter SubstitutionO(N·26·M2)O(N·M)
OptimalBidirectional BFSO(N·26·M2)O(N·M)
Common pitfalls
  • Counting edges, not words — count both ends.
  • Marking visited on dequeue — duplicate queueing.
  • No early exit when endWord ∉ list.
Interview tips
  • “Shortest” + unweighted graph ⇒ BFS; say it up front.
  • Compare neighbour costs: N·M scan vs 26·M generation.
  • Offer bidirectional BFS as the follow-up for long ladders.
Pattern
BFS on an implicit graph → minimum number of single-step transformations between states.
My notes saved in this browser