127. Word Ladder
Asked at 34Amazon67Apple65Meta57Bloomberg51Microsoft44Google42Navan100Yelp94Snap94Reddit90The Trade Desk78LinkedIn78Box71Okta71ByteDance66Citadel64Docusign64eBay64Tekion63ZScaler63Tesla62TikTok58Adobe55ServiceNow55Expedia54PhonePe53Oracle52Flipkart52Visa48Uber44Cisco37Salesforce35Capital One35tcs27
Problem
Transform beginWord into endWord by changing one letter at a time, where every intermediate word and endWord must be in wordList. Return the number of words in the shortest such sequence (including both ends), or 0 if none exists.
Example: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] → 5 (hit → hot → dot → dog → cog)
Constraints: up to 5000 words of length ≤ 10.
Words are nodes; edges connect words differing by one letter. BFS from beginWord. Generate neighbours by trying all 26 letters at each position (O(26·L) per word) and only keep words in the dictionary set.
hit -> hot -> dot -> dog -> cog length 5
\-> lot -> log -/
Complexity: O(N · L · 26).
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
words = set(wordList)
if endWord not in words:
return 0
q, steps = deque([beginWord]), 1
words.discard(beginWord)
while q:
for _ in range(len(q)):
w = q.popleft()
if w == endWord:
return steps
for i in range(len(w)):
for ch in string.ascii_lowercase:
nxt = w[:i] + ch + w[i + 1:]
if nxt in words:
words.remove(nxt)
q.append(nxt)
steps += 1
return 0
assert Solution().ladderLength("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"]) == 5
assert Solution().ladderLength("hit", "cog", ["hot", "dot", "dog", "lot", "log"]) == 0
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> words = new HashSet<>(wordList);
if (!words.contains(endWord)) return 0;
Deque<String> q = new ArrayDeque<>(List.of(beginWord));
for (int steps = 1; !q.isEmpty(); steps++) {
for (int k = q.size(); k > 0; k--) {
String w = q.poll();
if (w.equals(endWord)) return steps;
char[] cs = w.toCharArray();
for (int i = 0; i < cs.length; i++) {
char orig = cs[i];
for (char ch = 'a'; ch <= 'z'; ch++) {
cs[i] = ch;
String nxt = new String(cs);
if (words.remove(nxt)) q.add(nxt);
}
cs[i] = orig;
}
}
}
return 0;
}
}
func ladderLength(beginWord string, endWord string, wordList []string) int {
words := map[string]bool{}
for _, w := range wordList {
words[w] = true
}
if !words[endWord] {
return 0
}
delete(words, beginWord)
q := []string{beginWord}
for steps := 1; len(q) > 0; steps++ { // BFS, one level per step
next := []string{}
for _, w := range q {
if w == endWord {
return steps
}
b := []byte(w)
for i := range b {
orig := b[i]
for ch := byte('a'); ch <= 'z'; ch++ {
b[i] = ch
if s := string(b); words[s] {
delete(words, s) // visited
next = append(next, s)
}
}
b[i] = orig
}
}
q = next
}
return 0
}