Given two words beginWord and endWord, and a dictionary wordList, 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 and each transformed word must exist in the wordList. Return 0 if no such sequence exists.
Output: 5
Explanation: Shortest sequence: "hit" → "hot" → "dot" → "dog" → "cog", length 5.
Output: 0
Explanation: "cog" is not in wordList, so no valid sequence exists.
Model the problem as a graph where each word is a node and two nodes share an edge if they differ by exactly one character. We want the shortest path from beginWord to endWord, which BFS computes optimally.
- Add all words from wordList into a HashSet for O(1) lookup.
- Use BFS starting from beginWord, tracking the number of levels (transformations).
- For each word dequeued, try replacing every character with 'a' to 'z'. If the resulting word is in the word set, enqueue it and remove it from the set (to avoid revisiting).
- When endWord is reached, return the current level count. If the queue empties, return 0.
Complexity Analysis:
Time complexity: O(M² × N) where M is the length of each word and N is the number of words in the list. For each of the N words we try M positions with 26 characters and constructing the new string takes O(M).
Space complexity: O(M × N) for the word set and BFS queue.