Try it first — give it 40 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get a beginWord, an endWord, and a dictionary wordList. All words have the same length and use lowercase letters. A ladder is a sequence of words that starts at beginWord and ends at endWord, where each step changes exactly one letter and every word after the first must be in wordList. Return the number of words in the shortest ladder, or 0 if none exists. beginWord doesn't have to be in the list. Word length M is at most 10, and the list can hold up to 5000 words.
Example: hit → cog with ["hot","dot","dog","lot","log","cog"] → 5, via hit → hot → dot → dog → cog. That's 5 words, which is 4 changes.
Start with brute force
Build the graph explicitly. For every pair of words, check whether they differ in exactly one letter (O(M) per pair), and if so, add an edge. Then run BFS from beginWord.
Building that graph means comparing every pair: with N = 5000 and M = 10, that's about 5000²/2 × 10 ≈ 1.25 × 10⁸ character comparisons before BFS even starts. That's borderline in C++ and too slow in Python. A DFS that tries every possible ladder is far worse, because it's exponential.
Building the intuition
First, name what you're looking at. Each word is a node. Two words are joined by an edge if they differ in one letter. Every step costs the same (one change), so the graph is unweighted. And "shortest sequence" in an unweighted graph means BFS, the same level-by-level search you used in Rotting Oranges: everything one step away, then everything two steps away, and so on. The first time BFS reaches endWord, it got there by a shortest route.
The real question is how to find a word's neighbours without comparing it to all N words. Turn it around. Instead of asking "which dictionary words are one letter away from hot?", generate every string one letter away from hot and ask "is this a dictionary word?":
- position 0:
aot, bot, cot, …, zot - position 1:
hat, hbt, …, hzt - position 2:
hoa, hob, …, hoz
That's 26 × M candidates, at most 260, and a hash set checks each one in O(M). That beats scanning 5000 words when the dictionary is big.
One more trick does two jobs at once. Keep the dictionary in a set called unvisited, and delete a word from it the moment you put it in the queue. Now the set means "real words I haven't reached yet", so you can never queue a word twice, and you don't need a separate visited set.
The optimal approach
- Put
wordListin a hash setunvisited. IfendWordisn't in it, return0. - Remove
beginWordfromunvisited, putbeginWordin a queue, and setsteps = 1. - While the queue isn't empty, process one full level (all words currently in the queue):
- pop
word; if it equalsendWord, returnsteps; - for each position
iand each lettercother thanword[i], formnext; ifnextis inunvisited, remove it and enqueue it.
- pop
- After each level,
steps += 1. - If the queue empties, return
0.
The subtle detail is marking a word visited when you enqueue it, not when you pop it. If you wait until you pop it, the same word can be queued by several parents on the same level. The answer stays correct, but the queue can balloon and time out.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
from collections import deque
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
unvisited = set(wordList) # O(1) "is this a real word I haven't used yet?"
if endWord not in unvisited:
return 0
unvisited.discard(beginWord)
queue = deque([beginWord])
steps = 1 # number of words in the sequence, counting beginWord
while queue:
for _ in range(len(queue)): # one full BFS level = one more word in the ladder
word = queue.popleft()
if word == endWord:
return steps
chars = list(word)
for i in range(len(chars)):
original = chars[i]
for c in "abcdefghijklmnopqrstuvwxyz":
if c == original:
continue
chars[i] = c
nxt = "".join(chars)
if nxt in unvisited:
unvisited.remove(nxt) # mark visited when we enqueue, not when we pop
queue.append(nxt)
chars[i] = original # undo before moving to the next position
steps += 1
return 0class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> unvisited(wordList.begin(), wordList.end());
if (!unvisited.count(endWord)) return 0;
unvisited.erase(beginWord);
queue<string> q;
q.push(beginWord);
int steps = 1; // number of words in the sequence, counting beginWord
while (!q.empty()) {
for (int k = q.size(); k > 0; k--) { // one BFS level = one more word
string word = q.front();
q.pop();
if (word == endWord) return steps;
for (int i = 0; i < (int)word.size(); i++) {
char original = word[i];
for (char c = 'a'; c <= 'z'; c++) {
if (c == original) continue;
word[i] = c;
if (unvisited.count(word)) {
unvisited.erase(word); // mark visited when we enqueue
q.push(word);
}
}
word[i] = original; // undo before the next position
}
}
steps++;
}
return 0;
}
};class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> unvisited = new HashSet<>(wordList);
if (!unvisited.contains(endWord)) return 0;
unvisited.remove(beginWord);
Deque<String> queue = new ArrayDeque<>();
queue.add(beginWord);
int steps = 1; // number of words in the sequence, counting beginWord
while (!queue.isEmpty()) {
for (int k = queue.size(); k > 0; k--) { // one BFS level = one more word
String word = queue.poll();
if (word.equals(endWord)) return steps;
char[] chars = word.toCharArray();
for (int i = 0; i < chars.length; i++) {
char original = chars[i];
for (char c = 'a'; c <= 'z'; c++) {
if (c == original) continue;
chars[i] = c;
String next = new String(chars);
if (unvisited.remove(next)) { // true only if it was there: mark visited on enqueue
queue.add(next);
}
}
chars[i] = original; // undo before the next position
}
}
steps++;
}
return 0;
}
}/**
* @param {string} beginWord
* @param {string} endWord
* @param {string[]} wordList
* @return {number}
*/
var ladderLength = function (beginWord, endWord, wordList) {
const unvisited = new Set(wordList);
if (!unvisited.has(endWord)) return 0;
unvisited.delete(beginWord);
let queue = [beginWord];
let steps = 1; // number of words in the sequence, counting beginWord
while (queue.length) {
const nextLevel = []; // one BFS level = one more word
for (const word of queue) {
if (word === endWord) return steps;
const chars = word.split("");
for (let i = 0; i < chars.length; i++) {
const original = chars[i];
for (let code = 97; code <= 122; code++) { // 'a'..'z'
const c = String.fromCharCode(code);
if (c === original) continue;
chars[i] = c;
const next = chars.join("");
if (unvisited.has(next)) {
unvisited.delete(next); // mark visited when we enqueue
nextLevel.push(next);
}
}
chars[i] = original; // undo before the next position
}
}
queue = nextLevel;
steps++;
}
return 0;
};Dry run
hit → cog, list [hot, dot, dog, lot, log, cog]
Level (steps) | Queue at start of level | Newly enqueued (and removed from unvisited) |
|---|---|---|
| 1 | hit | hot |
| 2 | hot | dot, lot |
| 3 | dot, lot | dog (from dot), log (from lot) |
| 4 | dog, log | cog (from dog). log finds cog already removed. |
| 5 | cog | popped, equals endWord → return 5 |
Complexity
- Time: O(N · M² · 26). Each word is popped at most once. For it we try
Mpositions × 26 letters, and each candidate costs O(M) to build and hash. - Space: O(N · M) for the set and the queue, which hold at most
Nwords of lengthM.
Edge cases and traps
endWordnot in the list. The answer is0immediately. Check it first, or BFS wastes time exploring.- Returning changes instead of words. The answer counts words, so
stepsstarts at 1 forbeginWord.hot → dotis2. - Marking visited on pop. It's still correct, but duplicate queue entries can make it time out.
- Forgetting to restore the letter. After trying all 26 letters at position
i, put the original back before moving toi + 1, or you'll be changing two letters at once. - Using DFS. DFS finds a ladder, not the shortest one.
Say it in the interview
"Words are nodes, one-letter changes are edges, and every edge costs the same, so the shortest ladder is a BFS. I don't build the graph. For each word I try all 26 letters at each position and check a hash set of unvisited dictionary words. I remove a word from the set when I enqueue it, so nothing is queued twice. I count BFS levels and return the level where I pop endWord. That's O(N · M² · 26) time and O(N · M) space."
Follow-ups interviewers ask
- "Can you make it faster?" Bidirectional BFS: search from both ends and always expand the smaller frontier, stopping when they meet. The worst case is the same, but it explores far fewer words in practice.
- "What if you need the actual ladders?" That's Word Ladder II. Run BFS to record each word's parents on shortest paths, then backtrack from
endWordto list every ladder. - "Another way to find neighbours?" Map wildcard patterns like
h*tto the words that match them. Words that share a pattern are neighbours. It uses more memory, but it avoids trying letters that lead nowhere.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free