Word Ladder
01 · Problem
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.
02 · Examples
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
5
One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> "cog", which is 5 words long.
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
0
The endWord "cog" is not in wordList, so no valid transformation sequence exists.
beginWord = "a", endWord = "c", wordList = ["a","b","c"]
2
The transformation "a" -> "c" changes one letter and is 2 words long.
03 · Constraints
- 011 <= beginWord.length <= 10
- 02endWord.length == beginWord.length
- 031 <= wordList.length <= 5000
- 04wordList[i].length == beginWord.length
- 05beginWord, endWord, and wordList[i] consist of lowercase English letters.
- 06beginWord != endWord
- 07All the words in wordList are unique.
04 · Optimal complexity
- Time
- O(M^2 * N)
- Space
- O(M^2 * N)
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.