InterviewPrepKit

Home / Coding / Graphs

Word Ladder

hard Original ↗
Solving tips
  • Words are nodes, edges join words differing by one letter, all edges cost 1, so shortest chain = BFS; the answer counts both endpoints so start the step counter at 1 (a direct hop returns 2).
  • Check endWord in wordList up front and return 0 if absent; otherwise BFS could wander the whole graph for nothing.
  • Neighbor generation dominates: either try 26 letters x L positions with set-membership, or precompute wildcard buckets like h*t so one-edit words share a key; both are ~O(N*L^2).
  • Pitfall: mark words visited on enqueue (not dequeue) to avoid re-queuing; for large lists bidirectional BFS (always expand the smaller frontier) roughly square-roots the explored nodes.

Problem

You’re given two words, beginWord and endWord, and a list wordList. A transformation sequence is a chain of words beginWord → w1 → w2 → … → endWord where:

  • every adjacent pair differs by exactly one letter,
  • every word after beginWord is present in wordList (beginWord itself need not be),
  • endWord must be in wordList for any sequence to exist.

Return the number of words in the shortest such sequence (counting both ends), or 0 if no sequence exists. All words have the same length and consist of lowercase letters.

Examples

  • beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]5 — the chain hit → hot → dot → dog → cog has 5 words.
  • beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]0cog isn’t in the list, so endWord is unreachable.
  • beginWord = "a", endWord = "c", wordList = ["a","b","c"]2a → c differs by one letter and c is in the list.

Constraints

  • All words share the same length L (typically 1 ≤ L ≤ 10).
  • wordList can hold thousands of words; words are unique.
  • Word comparison is single-letter substitution only — no insertions or deletions.

Think about it first

Hint 1 Build a graph: each word is a node, and two words are connected iff they differ by exactly one letter. You want the fewest nodes on a path from beginWord to endWord — a shortest path on an unweighted graph.
Hint 2 Unweighted shortest path ⇒ BFS from beginWord. The first time you dequeue endWord, the number of levels you've descended is the answer. Track a visited set so words aren't re-enqueued.
Hint 3 Finding neighbors is the cost center. Two options: (a) for each of the L positions, try all 26 letters and test membership in a set; (b) precompute "wildcard" buckets like h*t so all words one edit apart share a key. For an extra speedup, run BFS from both ends and stop when they meet (bidirectional BFS).
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.