Problem 44 · Graphs
Word Ladder
01Problem
Given beginWord, endWord and a word list, return the number of words in the shortest transformation sequence changing one letter at a time, with every intermediate word in the list; return 0 if impossible.
02Key insight
Unweighted shortest path means BFS. Bucket words by wildcard patterns (h*t) so neighbor generation is O(L) lookups instead of comparing against every word; bidirectional BFS further shrinks the frontier.
03Solution
Try it first.
TimeO(N*L^2)
SpaceO(N*L^2)
tests.py · 3 passing
tests.pypython3 lines
assert ladder_length("hit", "cog", ["hot","dot","dog","lot","log","cog"]) == 5
assert ladder_length("hit", "cog", ["hot","dot","dog","lot","log"]) == 0
assert ladder_length("a", "c", ["a","b","c"]) == 204Staff-level follow-up
Dictionary of 100M words? Precompute the wildcard index offline in a KV store and run bidirectional BFS, which explores ~2*b^(d/2) nodes instead of b^d.