Menu
CoddyTech

Word Ladder

You get two words, beginWord and endWord, and a list of words wordList. A ladder 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, so endWord must be in it; beginWord need not be.

Return the number of words in the shortest ladder, counting both ends, or 0 if there is none.

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 a ladder needs at least 4 words, and lead, load, goad, gold has 4. lend and lewd are dead ends.
challenge icon

Follow-up

Can you return one shortest ladder itself, the words in order, instead of its length?

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

Test #1

Test #2

Test #3

Arguments

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

Expected Output

4