v9.1.1
Menu

Word Ladder

hardFREETrees & GraphsGoogle DSA

Given two words beginWord and endWord, and a word list, return the number of words in the shortest transformation sequence from beginWord to endWord, such that:

  • Only one letter can be changed at a time.
  • Each transformed word must exist in the word list.

Return 0 if no such transformation sequence exists. Note that beginWord does not need to be in the word list.

Example

Input
hit
cog
hot,dot,dog,lot,log,cog
Output
5
Reasoning
  • The transformation sequence starts with the beginWord "hit" and explores neighboring words by changing one letter at a time.
  • The sequence proceeds as follows: "hit" →\rightarrow "hot" →\rightarrow "dot" →\rightarrow "dog" →\rightarrow "cog", with each word being in the given word list.
  • This sequence has a length of 55, which is the shortest possible transformation sequence from "hit" to "cog".
  • Since no shorter sequence exists, the output is 55, representing the number of words in this shortest transformation sequence.

Constraints

  • 1 <= beginWord.length <= 10
  • endWord.length == beginWord.length
  • 1 <= len(wordList) <= 5000
  • All words have the same length
  • Words consist of lowercase English letters

Learn this in

More from Google DSA

solution.py

Test results

Sign in to run your code against the test cases.