TRT
Sign in
hardAdvancedLeetCode#BFS on an implicit graph#wildcard buckets

Word ladder

Find the length of the shortest chain of one-letter changes from one word to another through a dictionary, with BFS over an implicit graph.

The Runtime Theory Team1 min read
Taught inBreadth-first searchPro — members onlyBreadth-first search explores a graph in rings of increasing distance from the start, using a queue and a visited set. In an unweighted graph, the first time it reaches a vertex is along a shortest path.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inbeginWord = hit, endWord = cog, wordList = [hot, dot, dog, lot, log, cog]

out5

inbeginWord = hit, endWord = cog, wordList = [hot, dot, dog, lot, log]

out0

inbeginWord = a, endWord = c, wordList = [a, b, c]

out2

Return the number of words in the shortest transformation sequence from beginWord to endWord, changing one letter at a time, where every intermediate word is in the word list. Return 0 if none exists.

Before you code

Each word is a vertex; two words are neighbors if they differ in exactly one position. The graph is never built in full: generate a word's neighbors when you dequeue it.

Hints

  1. Put the word list in a set for O(1) membership.
  2. For each position and each letter a–z, form the candidate and check the set. Remove words from the set when you enqueue them, which doubles as the visited set.
  3. Faster neighbor lookup: group words by patterns such as h*t.
  4. Bidirectional BFS from both ends can cut the work dramatically.

Production & complexity notes

When solving Word ladder on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Breadth-first search to reinforce the underlying pattern.

What it practices

BFS shortest paths on a graph defined by a rule, from Breadth-first search.

Not started

Sign in to save your learning progress.

Sign in to save