Word Ladder II

hard

Given beginWord, endWord, and a wordList, return all shortest transformation sequences from beginWord to endWord, where each step changes exactly one letter and every intermediate word is in wordList. Return each sequence as its words joined by -> (e.g. "hit->hot->...->cog"); the order of the returned sequences does not matter. Return an empty list if no sequence exists.

Hints

First BFS from beginWord to record each word's distance from the start.
An edge lies on a shortest path iff it changes the distance by exactly one.
DFS backward from endWord following only those edges to enumerate all shortest ladders.

Common doubts

Storing every partial path in the BFS queue can blow up memory; distances plus a backward DFS keep only O(N·L) state and reconstruct paths one at a time.
Only step to a neighbour whose distance is one less than the current word's — those edges are exactly the ones on some shortest path.
No — the set of shortest sequences is the answer; here they're sorted for a canonical form.

Interview follow-ups

Searching from both ends and meeting in the middle shrinks the explored frontier, useful for large dictionaries.
Many independent one-letter choices at each level multiply into exponentially many shortest paths.

Fun facts

  • LeetCode 126 — the 'return all paths' escalation of Word Ladder.
  • The distance-gradient DFS is the general recipe for enumerating all shortest paths in any unweighted graph.

Asked at

AmazonFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: beginWord = "hit", endWord = "cog", wordList = [hot,dot,dog,lot,log,cog]
Output: ["hit->hot->dot->dog->cog", "hit->hot->lot->log->cog"]
Both ladders have length 5; no shorter one exists.
Example 2
Input: beginWord = "hit", endWord = "cog", wordList = [hot,dot,dog,lot,log]
Output: []
endWord 'cog' isn't reachable.
Constraints

- 1 <= word length <= 10 - 1 <= wordList.length <= 500 - all words have the same length - all words are lowercase and distinct

Solve this problem →