You are given a start word beginWord, an end word endWord and a list of words wordList, all the same length. A ladder goes from the start word to the end word one step at a time: each step changes exactly one letter, and every word you land on must be in the list. The start word itself does not have to be in the list.
Return how many words the shortest ladder has, counting both ends. If no ladder exists, return 0.
Example 1
Input: beginWord = "cat", endWord = "dog",
wordList = ["cot", "cut", "dot", "cog", "dog"]
Output: 4
Why: cat → cot → dot → dog2 more examples and the constraints
Example 2
Input: beginWord = "cat", endWord = "dog",
wordList = ["cot", "cut", "dot", "cog"]
Output: 0
Why: dog is not in the list, so no ladder can end on itExample 3
Input: beginWord = "a", endWord = "c", wordList = ["b", "c"] Output: 2 Why: a → c changes one letter
Constraints
- 1 ≤ word length ≤ 10
- 1 ≤ number of words in the list ≤ 5,000
- All words are lower-case English letters and the same length
- The list has no repeats, and beginWord ≠ endWord
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Build the graph from every pairO(n²·L)
- BFS, changing one letter at a timeO(n·L·26)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 5,000 words of 5 letters | Verdict |
|---|---|---|---|
| Build the graph from every pair | O(n²·L) | Mention it, then move on | |
| BFS, changing one letter at a time | O(n·L·26) | Best; no graph needed |
n = number of words, L = word length.
Edge cases to test
- End word not in the list. Example 2: return 0 at once.
- One step away. Example 3: the answer is 2, both ends counted.
- No path. The end word is listed, but no chain of one-letter changes reaches it: 0.
- Start word in the list. It may appear in the list; it must not be counted twice or revisited.
Common mistakes
- Counting the steps (changes) instead of the words: the answer is steps + 1.
- Marking a word as visited when it is popped instead of when it is queued, so it gets queued many times.
- Using depth-first search, which finds a ladder but not the shortest one.
How to talk through it
- 1Clarify. Does the count include both ends? Must the start word be in the list?
- 2Name the graph. Words are nodes, one-letter changes are edges, shortest ladder means BFS.
- 3Give the slow edges. Comparing every pair is O(n²·L); too slow for 5,000 words.
- 4Generate neighbours. Try 26 letters in each spot and look each one up in a set; remove words as you queue them.
- 5Test out loud. Run the missing end word, the one-step case and Example 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?