oneby7

Advanced Graphs Weighted shortest paths

476. Word Ladder II

Hard

You are given two words, beginWord and endWord, and a list of words, wordList. All of them have the same length.

A ladder is a sequence of words that starts with beginWord and ends with endWord. Each word in it differs from the word before it in exactly one position. Every word after beginWord must be in wordList; beginWord itself does not have to be.

Return every shortest ladder, each as its list of words from beginWord to endWord. The ladders may come in any order. If no ladder exists, return an empty list.

Example 1

Input: beginWord = "cat" endWord = "dog" wordList = ["hot", "cot", "dog", "cog", "dot", "hog", "cut"]

Output: [["cat","cot","cog","dog"], ["cat","cot","dot","dog"]]

Explanation: Both ladders have four words, and no ladder is shorter. cat → cot → hot → hog → dog is also a ladder, but it has five words, so it is not returned.

Example 2

Input: beginWord = "tree" endWord = "leaf" wordList = ["free", "flee", "flea", "leaf"]

Output: []

Explanation: tree → free → flee → flea works, but leaf differs from every other word in more than one position. So no ladder reaches it, even though it is in wordList.

Example 3

Input: beginWord = "a" endWord = "c" wordList = ["a", "b", "c"]

Output: [["a","c"]]

Explanation: a and c differ in their only letter, so the ladder a → c has two words. a → b → c has three. beginWord is in the list here, and it still appears only once, at the start.

Check your understanding

Work out the answer for this input before you write any code.

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

Constraints

  • 1 ≤ beginWord.length ≤ 10
  • endWord.length == beginWord.length
  • 1 ≤ wordList.length ≤ 5000
  • wordList[i].length == beginWord.length
  • beginWord, endWord and every wordList[i] hold only lowercase English letters.
  • beginWord != endWord
  • The words in wordList are distinct.
  • The shortest ladders hold at most 105 words in all.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.