FastPrepShortest Word Transformation Sequence
Problem · Breadth First Search

Shortest Word Transformation Sequence

Learn this problem
HardReddit logoRedditFULLTIMEPHONE SCREEN

Problem statement

You are given two different words, beginWord and endWord, and a dictionary wordList. A transformation changes exactly one letter, and every transformed word, including endWord, must appear in the dictionary.

Return the number of words in the shortest valid transformation sequence from beginWord through endWord, counting both endpoints. Return 0 when no valid sequence exists.

Function

ladderLength(beginWord: String, endWord: String, wordList: String[]) → int

Examples

Example 1

beginWord = "hit"endWord = "cog"wordList = ["hot","dot","dog","lot","log","cog"]return = 5

One shortest sequence is hit → hot → dot → dog → cog, which contains five words.

Example 2

beginWord = "hit"endWord = "cog"wordList = ["hot","dot","dog","lot","log"]return = 0

The endpoint is absent from the dictionary, so no valid transformation sequence exists.

Example 3

beginWord = "a"endWord = "c"wordList = ["a","b","c"]return = 2

Changing a directly to c uses two words.

Constraints

  • 1 <= beginWord.length == endWord.length <= 10.
  • 1 <= wordList.length <= 5000.
  • All words have the same length and contain only lowercase English letters.
  • beginWord and endWord are different.
  • The dictionary contains no duplicate words.

More Reddit problems

drafts saved locally
public int ladderLength(String beginWord, String endWord, String[] wordList) {
    // Write your solution here.
}
beginWord"hit"
endWord"cog"
wordList["hot","dot","dog","lot","log","cog"]
expected5
checking account