Word Ladder
Find the fewest one-letter changes between two words
DSA, Hard, Graphs
Which structure or algorithm, and what does it cost.
You turn the word start into the word goal one letter at a time. Each step changes exactly one letter, and the new word must be in the list words. The word start does not have to be in words. All words are lowercase and have the same length, and start differs from goal. Write ladder_steps(start, goal, words). It returns the fewest steps, or -1 if the change cannot be done.
Examples
Constraints
- 1 <= word length <= 8.
- 0 <= number of words <= 6,000, and no word repeats.
- All words use the letters a to z.
Your answer must contain
- Why a breadth-first search gives the fewest steps; how the neighbours are found quickly; the method; code; time and memory cost; a hand trace of example 1; the goal missing from the list.
Target Aim for O(N * L^2) time and memory, where N is the number of words and L is the word length.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Think of each word as a dot, and join two words that differ by one letter. What are you being asked to find in this picture?
Hint 2 the approach
Fewest steps on an unweighted picture comes from spreading outward from start, one step at a time. The hard part is finding a word's neighbours quickly.
Hint 3 the key step
Group words by pattern: replace one letter with a star, so cat and cot share c*t. Words in the same group are neighbours. Search from start through the groups.
Walkthrough
Full walkthrough brute force to best
Brute force
Try every chain. From start, step to each unused word that is one letter away, and keep going until you reach goal. Keep the shortest chain found. With N words there can be about N! chains, so this only works for a handful of words.
Better method
Breadth-first search from start, where a word's neighbours are found by scanning the whole list and comparing letters. It finds the fewest steps, because a queue visits words in order of their step count. Each of up to N words scans N words at L letters each, so it costs O(N^2 * L) time.
Best method
Think of each word as a point and join two words that differ in exactly one letter. The fewest steps is the shortest path, which a breadth-first search finds. The slow part is finding a word's neighbours. Group the words first: for each word and each position, replace that letter with a star to make a pattern. Words with the same pattern differ at most in that one position, so they are neighbours. Store each pattern with its list of words, including start. Then search from start with a queue of words and their step counts. Take a word, look up its L patterns, and queue every word in those groups that is not seen yet, with one more step. Mark a word seen when you queue it. When you take goal off the queue, its step count is the answer. If the queue empties, or goal is not in the list, the answer is -1.
Hand trace
Example 1: cold has the pattern co*d, which holds cord, so cord is queued at 1. Taking cord (1): *ord holds word and c*rd holds card, so word and card are queued at 2. Taking word (2): w*rd holds ward and wo*d holds wood, so ward and wood are queued at 3. Taking card (2): its neighbours are already seen. Taking ward (3): war* holds warm, so warm is queued at 4. Taking wood (3) adds nothing. Taking warm (4): it is the goal, so the answer is 4.
Code
from collections import deque, defaultdict
def ladder_steps(start, goal, words):
if goal not in words:
return -1
groups = defaultdict(list) # "c*t" -> the words that fit it
for w in [start] + words:
for i in range(len(w)):
groups[w[:i] + '*' + w[i + 1:]].append(w)
seen = {start}
todo = deque([(start, 0)])
while todo:
w, steps = todo.popleft()
if w == goal:
return steps
for i in range(len(w)):
for nxt in groups[w[:i] + '*' + w[i + 1:]]:
if nxt not in seen:
seen.add(nxt) # mark when queued
todo.append((nxt, steps + 1))
return -1Time and memory
O(N * L^2) time and memory. Building the patterns makes N * L patterns of length L. Each word is queued once and looks up L groups, and a group holds at most about 26 words, because its words differ only in one letter. The groups hold N * L entries.
Common mistakes
- Counting words instead of steps. The answer counts changes, so a chain of 5 words is 4 steps.
- Marking a word seen only when it leaves the queue. A word can then be queued many times, so mark it when you queue it.
- Stepping to a word that is not in the list. Every word you step to, including the last, must be in the list, so a missing goal gives -1.