hard

Word Ladder

Given a start word, an end word and a dictionary of equal-length words, find the length of the shortest transformation sequence from start to end where each step changes exactly one letter and every intermediate word is in the dictionary. Return 0 if impossible.

Constraints
  • 1 ≤ word length ≤ 10
  • 1 ≤ wordList.length ≤ 5000
  • Lowercase letters, all words distinct
Examples
in: begin = "hit", end = "cog", list = ["hot","dot","dog","lot","log","cog"]
out: 5
hit → hot → dot → dog → cog.
Recognition clues
  • Shortest sequence of transformations
  • Every step has the same cost — unweighted graph
  • Neighbours are generated by substituting one letter
Pattern
Breadth-First Search

BFS explores in rings of increasing distance, so the first time it reaches a node it has found a shortest path in terms of edge count. "Minimum number of moves" on any state space where each move costs 1 is BFS, whether the states are grid cells, words, or puzzle configurations.

Solution

Treat words as nodes with an edge between words differing in one letter. Run BFS from the start word: for each dequeued word, generate all L · 26 one-letter variants, and for each variant present in the dictionary set, remove it from the set (marking visited) and enqueue it with depth + 1. The first time the end word is generated, its depth is the answer. BFS finds the shortest path because all edges cost one.

time O(N · L · 26)space O(N · L)
Alternative approaches
  • Bidirectional BFS from both ends dramatically shrinks the frontier. Precomputing wildcard patterns like h*t as adjacency buckets avoids the 26-letter loop.
Code it yourself
Solve in
Hints: