Word Ladder
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
- Every adjacent pair of words differs by a single letter.
- Every
sifor1 <= i <= kis inwordList. Note thatbeginWorddoes not need to be inwordList. sk == endWord
Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: One shortest transformation sequence is
"hit" -> "hot" -> "dot" -> "dog" -> "cog", which is 5 words long.
Example 2:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore
there is no valid transformation sequence.
Example 3:
Input: beginWord = "a", endWord = "c", wordList = ["a","b","c"]
Output: 2
Explanation: The shortest transformation is "a" -> "c" (1 letter change), which is 2 words.
Examples
Example 1
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> "cog", which is 5 words long.
Example 2
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, so no valid transformation sequence exists.
Example 3
Input: beginWord = "a", endWord = "c", wordList = ["a","b","c"]
Output: 2
Explanation: The transformation "a" -> "c" changes one letter and is 2 words long.
Constraints
- -1 <= beginWord.length <= 10
- -endWord.length == beginWord.length
- -1 <= wordList.length <= 5000
- -wordList[i].length == beginWord.length
- -beginWord, endWord, and wordList[i] consist of lowercase English letters.
- -beginWord != endWord
- -All the words in wordList are unique.
Optimal Complexity
Time
O(M^2 * N)
Space
O(M^2 * N)
Practice this problem with an AI interviewer
TechInView conducts a full voice mock interview — the AI asks clarifying questions, evaluates your approach, watches you code, and scores you on 5 dimensions. Just like a real FAANG interview.
Start a free interview