Search~30 min2s · 256 MBtarget O(W × L × (L + 26)) time, O(W × L) spaceclassic twin: lc-127bfs
A search app suggests related searches by editing a term one letter at a time. A suggestion chain starts at one word and ends at another. Every word after the first must be a term the app has indexed.
Your team lead says: "For two words of the same length, tell me the fewest single-letter changes that lead from one to the other, through indexed terms only."
You work on the suggestion planner. Each step changes exactly one letter, and the word keeps its length.
Write ladder_steps(begin, goal, terms).
begin and goal are lowercase words of the same length.terms lists the indexed terms. They are lowercase words of that length too, and may repeat.terms. The first word, begin, does not need to be in terms.begin to goal, or -1 when no chain exists. If begin == goal, return 0.Input: begin = "cold", goal = "warm", terms = ["cord", "card", "ward", "warm", "word", "corm", "wold"]
Output: 4The search keeps a queue of words, oldest first. A word's steps are fixed when it joins the queue.
| Word taken from the queue | Steps | New words queued |
|---|---|---|
| cold | 0 | wold, cord |
| wold | 1 | word |
| cord | 1 | card, corm |
| word | 2 | ward |
| card | 2 | none |
| corm | 2 | none |
| ward | 3 | warm |
| warm | 4 | goal reached |
The first chain to reach "warm" has 4 steps, and no shorter one exists.
Input: begin = "cold", goal = "warm", terms = ["cord", "card", "ward", "word", "corm", "wold"]
Output: -1"warm" is not an indexed term, so no step can end on it.
Input: begin = "same", goal = "same", terms = []
Output: 0The word is already the goal.
1 ≤ len(begin) = len(goal) ≤ 80 ≤ len(terms) ≤ 10,000, and every term has the same length as begina to z onlyComparing every pair of terms letter by letter takes about 10,000 × 10,000 × 8, which is 800 million comparisons. Grouping terms by pattern, with one letter replaced by a star, helps. Then the neighbours of a word take at most 8 lookups, one for each letter position.