Word Ladder

50 min · ladderLength()

Changing one letter can turn cold into cord. A few careful changes can turn it into warm — but every word along the way has to be approved.

Given beginWord, endWord, and a unique wordList, transform the beginning word by changing exactly one letter at a time. Every word after beginWord, including endWord, must appear in wordList.

Return the number of words in the shortest valid sequence, counting both ends. Return 0 when no sequence exists.

Ground rules:

  • Every word has the same length and uses lowercase English letters.
  • beginWord doesn't have to appear in wordList.
  • endWord must appear in wordList for any sequence to be valid.
  • When beginWord == endWord and that word is in the list, the answer is 1.

Constraints

  • 1 <= beginWord.length <= 10
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 5_000
  • Every wordList[i] has the same length as beginWord.
  • All words contain only lowercase English letters.
  • Words in wordList are unique.

Hints

Turn words into states

Two words are neighbors when they differ at exactly one position. A shortest path through those neighbor links is the transformation you want.

Avoid comparing every pair

cold can be represented by patterns such as *old, c*ld, co*d, and col*. Words sharing one of those patterns differ in at most the hidden position.

Search by sequence length

Start breadth-first search at beginWord with length 1. Mark a word when you add it to the queue, so two patterns can't schedule the same word twice.

Follow-up

How would a search growing from both beginWord and endWord reduce the work when the dictionary is large and the shortest ladder is deep?

Visible cases

Examples

Example 1

ready
Input
beginWord = "hit"
endWord = "cog"
wordList = [
  "hot",
  "dot",
  "dog",
  "lot",
  "log",
  "cog"
]
Expected
5
Why
one shortest sequence is hit → hot → dot → dog → cog

Example 2

ready
Input
beginWord = "hit"
endWord = "cog"
wordList = [
  "hot",
  "dot",
  "dog",
  "lot",
  "log"
]
Expected
0
Why
cog is absent from the dictionary, so no valid sequence can end there

Example 3

ready
Input
beginWord = "same"
endWord = "same"
wordList = [
  "same",
  "came"
]
Expected
1
Why
the starting word already equals the listed ending word

Interview signal

Asked at

AmazonGoogleMetaLinkedIn
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite