Word Ladder⚓︎
Description⚓︎
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
si
for1 <= i <= k
is inwordList
. Note thatbeginWord
does 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.
Constraints:
1 <= beginWord.length <= 10
endWord.length == beginWord.length
1 <= wordList.length <= 5000
wordList[i].length == beginWord.length
beginWord
,endWord
, andwordList[i]
consist of lowercase English letters.beginWord != endWord
- All the words in
wordList
are unique.
Solution⚓︎
Code with Comments:
Algorithm:
- Initialization: Convert the
wordList
into anunordered_set
for \(O(1)\) access. This helps in quickly checking if a word exists in the word list. Additionally, a queue for BFS and a map to track visited words are initialized. - Breadth-First Search (BFS): The algorithm uses BFS to find the shortest path from
beginWord
toendWord
. For each word, it iteratively changes each letter to all possible 26 letters and checks if the new word is in the word set. - Path Tracking: The
visitMap
keeps track of each word and the length of the shortest path to reach it frombeginWord
. - Termination: If
endWord
is reached, the shortest path length is returned. If BFS completes without findingendWord
, return 0.
Complexity Analysis:
- Time Complexity:
- The main contributing factor to time complexity is the double loop inside the BFS, where we iterate over each letter of the word and then over 26 possible replacements.
- For a word of length
L
and a total ofN
words in the word list, the worst-case time complexity is \(O(26NL)\). This is because we potentially explore \(26\) different transformations for each of the \(L\) characters in each of the \(N\) words. - Space Complexity:
- The space complexity is primarily dictated by the storage of the word set and the visit map.
- Both the
unordered_set
and theunordered_map
store a number of elements equal to the size of thewordList
, giving a space complexity of \(O(N)\). - Additionally, the queue in the worst case might store a significant number of words, but this also will not exceed \(O(N)\).