Word Ladder II

Hard · Graphs · Hash Table · String · Backtracking · Breadth-First Search

Problem

A transformation sequence from beginWord to endWord is a list of words that starts with beginWord, ends with endWord, changes exactly one letter from each word to the next, and uses only words from wordList after beginWord (beginWord itself need not be in the list).

Return every shortest transformation sequence, each as a list of words. The sequences may be in any order. If there is none, return an empty list.

Examples

Input: beginWord = "cold", endWord = "warm", wordList = ["cord","card","ward","warm","word","worm"]
Output: [["cold","cord","word","worm","warm"],["cold","cord","card","ward","warm"],["cold","cord","word","ward","warm"]]

Three different five-word routes are all shortest.

Input: beginWord = "cat", endWord = "dog", wordList = ["cot","cog"]
Output: []

"dog" is not in the list, so no sequence exists.

Input: beginWord = "ab", endWord = "cd", wordList = ["ad","cb","cd"]
Output: [["ab","ad","cd"],["ab","cb","cd"]]

Change the first letter first or the second letter first.

Constraints

Approaches

Follow-up

If you only needed how many shortest sequences there are, you could add counts level by level instead of listing paths, which stays fast even when there are billions: the first use case below. Searching from both ends at once also cuts down the levels explored on large dictionaries.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…