HardHash TableStringBreadth-First Search

1 approach, code in every language

Problem description

You are given two words, beginWord and endWord, together with a dictionary wordList.

A transformation sequence starts at beginWord and ends at endWord. At each step you may change exactly one letter, and every word produced after the first step must appear in wordList. Note that beginWord itself does not need to be in wordList.

Return the number of words in the shortest transformation sequence from beginWord to endWord. If no such sequence exists, return 0.

Example 1

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

One shortest sequence is "hit" -> "hot" -> "dot" -> "dog" -> "cog", which contains 5 words.

Example 2

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]

Output: 0

endWord "cog" is not present in wordList, so no valid sequence can end at it.

Constraints

  • 1 <= beginWord.length <= 10
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 5000
  • wordList[i].length == beginWord.length
  • beginWord, endWord, and wordList[i] consist of lowercase English letters
  • beginWord != endWord
  • All the words in wordList are unique

After the pattern

Now solve one you haven't seen.

Dial Code Rewrite is our own problem on the technique behind Word Ladder: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free