127. Word Ladder LeetCode Solution
In this guide, you will get 127. Word Ladder LeetCode Solution with the best time and space complexity. The solution to Word Ladder problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Word Ladder solution in C++
- Word Ladder solution in Java
- Word Ladder solution in Python
- Additional Resources
Problem Statement of 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 si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
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, and wordList[i] consist of lowercase English letters.
beginWord != endWord
All the words in wordList are unique.
Complexity Analysis
- Time Complexity: O(|\texttt{wordList}| \cdot 26^{\texttt{wordlist[i]}})
- Space Complexity: O(|\texttt{wordList}|)
127. Word Ladder LeetCode Solution in C++
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordSet(wordList.begin(), wordList.end());
if (!wordSet.contains(endWord))
return 0;
queue<string> q{{beginWord}};
for (int step = 1; !q.empty(); ++step)
for (int sz = q.size(); sz > 0; --sz) {
string word = q.front();
q.pop();
for (int i = 0; i < word.length(); ++i) {
const char cache = word[i];
for (char c = 'a'; c <= 'z'; ++c) {
word[i] = c;
if (word == endWord)
return step + 1;
if (wordSet.contains(word)) {
q.push(word);
wordSet.erase(word);
}
}
word[i] = cache;
}
}
return 0;
}
};
/* code provided by PROGIEZ */
127. Word Ladder LeetCode Solution in Java
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> wordSet = new HashSet<>(wordList);
if (!wordSet.contains(endWord))
return 0;
Queue<String> q = new ArrayDeque<>(List.of(beginWord));
for (int step = 1; !q.isEmpty(); ++step)
for (int sz = q.size(); sz > 0; --sz) {
StringBuilder sb = new StringBuilder(q.poll());
for (int i = 0; i < sb.length(); ++i) {
final char cache = sb.charAt(i);
for (char c = 'a'; c <= 'z'; ++c) {
sb.setCharAt(i, c);
final String word = sb.toString();
if (word.equals(endWord))
return step + 1;
if (wordSet.contains(word)) {
q.offer(word);
wordSet.remove(word);
}
}
sb.setCharAt(i, cache);
}
}
return 0;
}
}
// code provided by PROGIEZ
127. Word Ladder LeetCode Solution in Python
class Solution:
def ladderLength(
self,
beginWord: str,
endWord: str,
wordList: list[str],
) -> int:
wordSet = set(wordList)
if endWord not in wordSet:
return 0
q = collections.deque([beginWord])
step = 1
while q:
for _ in range(len(q)):
wordList = list(q.popleft())
for i, cache in enumerate(wordList):
for c in string.ascii_lowercase:
wordList[i] = c
word = ''.join(wordList)
if word == endWord:
return step + 1
if word in wordSet:
q.append(word)
wordSet.remove(word)
wordList[i] = cache
step += 1
return 0
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.