Problem · Breadth First Search

Minimum Word Ladder Length

Learn this problem
HardSalesforce logoSalesforceFULLTIMEONSITE INTERVIEW
See Salesforce hiring insights

Problem statement

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

Return the number of words in the shortest valid sequence from beginWord through endWord, counting both endpoints. Return 0 when no sequence exists. If the two endpoints are equal, the answer is 1 only when that word appears in the dictionary.

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 ladder exists.

Example 3

beginWord = "same"endWord = "same"wordList = ["same","came"]return = 1

The endpoints already match and the endpoint appears in the dictionary.

Constraints

  • 1 <= beginWord.length == endWord.length <= 10.
  • 1 <= wordList.length <= 5000.
  • Every dictionary word has the same length as beginWord.
  • Words contain only lowercase English letters.

More Salesforce problems

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