 All Problems
Word Ladder
hard
hash table
string
breadth-first search
amazon
google
microsoft

A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words such that:

  • The first word is beginWord
  • The last word is endWord
  • Only one letter can be changed at a time
  • Each transformed word must exist in the wordList

Given beginWord, endWord, and wordList, return the number of words in the shortest transformation sequence, or 0 if no such sequence exists.

Example 1:

Input:
hit
cog
hot dot dog lot log cog
Output: 5

(hit → hot → dot → dog → cog, length 5)

Example 2:

Input:
hit
cog
hot dot dog lot log
Output: 0

Constraints:

  • 1 ≤ beginWord.length ≤ 10
  • endWord.length == beginWord.length
  • 1 ≤ wordList.length ≤ 5000
  • All words have the same length and consist of lowercase English letters

Input format: First line: beginWord. Second line: endWord. Third line: space-separated wordList.

Output format: Integer — shortest transformation sequence length, or 0.

Run to check your code against the sample cases, or submit to run every case