Word Ladder
Hard
Topics
Given beginWord, endWord, and a wordList, return the number of words in the shortest transformation sequence from begin to end (changing one letter at a time, each intermediate word in the list), or 0 if none. The count includes both endpoints.
Example 1
the shortest chain
Two words are neighbours when they differ in exactly one letter, which turns the word list into a graph and the question into a shortest path. The shaded chain is
hit → hot → dot → dog → cog, so the answer counts 5 words — words, not steps.The first chip is
beginWord; the rest are wordList.Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5
Example 2
cog is not reachable by single-letter edits through the given list (and the end word must itself be in the list), so the answer is 0.Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: 0
Constraints
- 1 <= word length <= 10
- 1 <= wordList.length <= 5000
- All words have the same length.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Words are nodes; an edge connects two words differing by one letter. The shortest transformation is a shortest path, so BFS from beginWord finds it in the fewest steps.
Approach
- Put wordList in a set; if endWord is absent, return 0.
- BFS from beginWord, tracking the level (sequence length).
- From each word, try all one-letter changes; enqueue those in the set and not yet visited.
Dry Run
beginWord = hit, endWord = cog, wordList = [hot, dot, dog, lot, log, cog]
pop (hit, 1) neighbours in the set: hot queue (hot, 2)
pop (hot, 2) neighbours: dot, lot queue (dot, 3) (lot, 3)
pop (dot, 3) neighbours: dog queue (dog, 4)
pop (lot, 3) neighbours: log queue (log, 4)
pop (dog, 4) neighbours: cog queue (cog, 5)
pop (log, 4) cog already seen, nothing queued
pop (cog, 5) equals endWord return 5
answer 5 (hit to hot to dot to dog to cog)
Two things the trace shows. The depth is stored with the word rather than
tracked separately, so there is no level bookkeeping. And `seen` is marked when
a word is QUEUED, not when it is popped -- log finds cog already seen and
queues nothing, which is what stops the same word entering the queue twice.Complexity
- Time — O(N * L * 26): for each of N words, L positions times 26 letters.
- Space — O(N * L): the visited set and queue.
Common Pitfalls
- Mark a word seen when you enqueue it, not when you pop it. Marking on pop lets the same word enter the queue many times before any of them is processed, and the run does not finish -- it times out rather than returning something wrong.
- Generating all 26 single-character substitutions is O(26 L) per word, which beats comparing against every word in the list when the list is large. That trade is the actual content of this problem.
Full Solution — all languages
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
words=set(wordList)
if endWord not in words: return 0
from collections import deque
q=deque([(beginWord,1)]); seen={beginWord}
while q:
w,d=q.popleft()
if w==endWord: return d
for i in range(len(w)):
for c in 'abcdefghijklmnopqrstuvwxyz':
nxt=w[:i]+c+w[i+1:]
if nxt in words and nxt not in seen:
seen.add(nxt); q.append((nxt,d+1))
return 0import java.util.*;
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<Object[]> q=new ArrayDeque<>();
q.add(new Object[]{beginWord,1});
Set<String> seen=new HashSet<>();
seen.add(beginWord);
while(!q.isEmpty()) {
Object[] cur=q.poll();
String w=(String)cur[0];
int d=(int)cur[1];
if(w.equals(endWord))return d;
char[] arr=w.toCharArray();
for(int i=0;i<arr.length;i++) {
char old=arr[i];
for(char c='a';c<='z';c++) {
arr[i]=c;
String nx=new String(arr);
if(words.contains(nx)&&!seen.contains(nx)) {
seen.add(nx);
q.add(new Object[]{nx,d+1});
}
}
arr[i]=old;
}
}
return 0;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> words(wordList.begin(),wordList.end());
if(!words.count(endWord))return 0;
queue<pair<string,int>> q;
q.push({beginWord,1});
unordered_set<string> seen;
seen.insert(beginWord);
while(!q.empty()) {
auto cur=q.front();
q.pop();
string w=cur.first;
int d=cur.second;
if(w==endWord)return d;
for(int i=0;i<(int)w.size();i++) {
string nx=w;
for(char c='a';c<='z';c++) {
nx[i]=c;
if(words.count(nx)&&!seen.count(nx)) {
seen.insert(nx);
q.push({nx,d+1});
}
}
}
}
return 0;
}
};/**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/ var ladderLength = function(beginWord, endWord, wordList) {
const words=new Set(wordList);
if(!words.has(endWord))return 0;
const q=[[beginWord,1]],seen=new Set([beginWord]);
let idx=0;
while(idx<q.length) {
const cur=q[idx++],w=cur[0],d=cur[1];
if(w===endWord)return d;
for(let i=0;i<w.length;i++)for(let c=97;c<123;c++) {
const nxt=w.slice(0,i)+String.fromCharCode(c)+w.slice(i+1);
if(words.has(nxt)&&!seen.has(nxt)) {
seen.add(nxt);
q.push([nxt,d+1]);
}
}
}
return 0;
};