Menu
CoddyTech

Word Ladder

You get two words, beginWord and endWord, and a list of words wordList. A ladder is a sequence of words that starts with beginWord, ends with endWord, and changes exactly one letter from each word to the next. Every word after beginWord must come from wordList.

Return the number of words in the shortest ladder, counting both ends, or 0 if no ladder exists. For example, cold, cord, card is a ladder of 3 words. beginWord does not have to be in wordList, but endWord does.

Function

ladderLength(beginWord: string, endWord: string, wordList: string-array) → integer
beginWordstring
the first word of the ladder
endWordstring
the word the ladder must reach
wordListstring-array
the words every later step must come from
Returnsinteger
the number of words in the shortest ladder, or 0 if there is none

Constraints

  • 1 ≤ beginWord.length ≤ 10
  • endWord and every word in wordList have the same length as beginWord.
  • 1 ≤ wordList.length ≤ 5000
  • All words hold only lowercase English letters.
  • beginWord != endWord
  • The words in wordList are all different. beginWord may or may not be one of them.

Examples

Input
beginWord = "lead"endWord = "gold"wordList = ["load", "goad", "gold", "lend", "lewd", "bold"]
Output
4
Explanation
lead and gold differ in three letters, so no ladder has fewer than 4 words, and lead, load, goad, gold has exactly 4. lend and lewd are one letter from lead too, but neither leads anywhere new, and bold can only be reached from gold itself.

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

Can you return one shortest ladder itself, the words in order, and not only its length?

Reset code
def ladderLength(beginWord, endWord, wordList):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

beginWord = "lead"
endWord = "gold"
wordList = ["load", "goad", "gold", "lend", "lewd", "bold"]

Expected

4