Home
DSA Patterns
Breadth-First Search
Word Ladder
Word Ladder (LeetCode 127)
Word Ladder (LeetCode 127): find the shortest sequence of one-letter changes from one word to another with BFS, visiting each word once, level by level.
Problem Understanding
Word Ladder: transform beginWord into endWord by changing one letter at a time, where every intermediate word must be in wordList. Return the number of words in the shortest such sequence, counting both ends, or 0 if none exists.
Example: hit → hot → dot → dog → cog has 5 words, so ladderLength("hit", "cog", [hot, dot, dog, lot, log, cog]) returns 5.
The Intuition: A Shortest Path in a Word Graph
Picture every word as a node, with an edge between two words that differ in exactly one letter. A ladder is a path, and the shortest ladder is the shortest path. Every edge has the same cost, so breadth-first search finds it.
- If
endWordis not in the list, return 0. - Start the queue with
beginWordat length 1. - Process one level at a time. For each word, try every one-letter change; any change still in the word set is removed from the set (visited) and queued.
- After each level, add 1 to the length. The first time
endWordis popped, return the length.
Removing words when they are queued is what keeps each word from being visited twice.
Word Ladder Visualization
HIT → COG · ONE LETTER AT A TIME
START BFS
length 1
word
:
length
1
Answer
:
Put the words in a set. Start the BFS queue with "hit"; a sequence of just it has length 1
Next
Take "hit" from level 1
wordList
begin end
Each row is one BFS level: the words first reached by a sequence of that length. The word being expanded is filled, the words it queues are shaded, and the end word turns green when it is reached.
Word Ladder Dry Run
Input: hit → cog, list [hot, dot, dog, lot, log, cog]
| Length | Words at this level |
|---|---|
| 1 | hit |
| 2 | hot |
| 3 | dot, lot |
| 4 | dog, log |
| 5 | cog |
cog is reached at length 5.
Word Ladder LeetCode Solution
Level-order BFS with a word set. C has no built-in hash set, so its snippet compares each word against the list directly (O(N² · L)), with a visited array.
Word Ladder Code
1var ladderLength = function(beginWord, endWord, wordList) {2 const words = new Set(wordList);3 if (!words.has(endWord)) return 0;4 let queue = [beginWord];5 let length = 1;6 while (queue.length) {7 const next = [];8 for (const word of queue) {9 if (word === endWord) return length;10 for (let i = 0; i < word.length; i++) {11 for (let c = 97; c <= 122; c++) {12 const nxt = word.slice(0, i) + String.fromCharCode(c) + word.slice(i + 1);13 if (words.delete(nxt)) next.push(nxt);14 }15 }16 }17 queue = next;18 length++;19 }20 return 0;21};
Word Ladder in Python, Java, C++, TypeScript and C
Word Ladder in Python
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
words = set(wordList)
if endWord not in words:
return 0
queue = deque([beginWord])
length = 1
while queue:
for _ in range(len(queue)):
word = queue.popleft()
if word == endWord:
return length
for i in range(len(word)):
for c in 'abcdefghijklmnopqrstuvwxyz':
nxt = word[:i] + c + word[i + 1:]
if nxt in words:
words.remove(nxt)
queue.append(nxt)
length += 1
return 0Word Ladder in Java
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> queue = new ArrayDeque<>(List.of(beginWord));
int length = 1;
while (!queue.isEmpty()) {
for (int size = queue.size(); size > 0; size--) {
String word = queue.poll();
if (word.equals(endWord)) return length;
char[] chars = word.toCharArray();
for (int i = 0; i < chars.length; i++) {
char original = chars[i];
for (char c = 'a'; c <= 'z'; c++) {
chars[i] = c;
String nxt = new String(chars);
if (words.remove(nxt)) queue.add(nxt);
}
chars[i] = original;
}
}
length++;
}
return 0;
}
}Word Ladder in C++
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<string> q;
q.push(beginWord);
int length = 1;
while (!q.empty()) {
for (int size = q.size(); size > 0; size--) {
string word = q.front(); q.pop();
if (word == endWord) return length;
for (int i = 0; i < (int)word.size(); i++) {
char original = word[i];
for (char c = 'a'; c <= 'z'; c++) {
word[i] = c;
if (words.erase(word)) q.push(word);
}
word[i] = original;
}
}
length++;
}
return 0;
}
};Word Ladder in TypeScript
function ladderLength(beginWord: string, endWord: string, wordList: string[]): number {
const words = new Set<string>(wordList);
if (!words.has(endWord)) return 0;
let queue: string[] = [beginWord];
let length = 1;
while (queue.length) {
const next: string[] = [];
for (const word of queue) {
if (word === endWord) return length;
for (let i = 0; i < word.length; i++) {
for (let c = 97; c <= 122; c++) {
const nxt = word.slice(0, i) + String.fromCharCode(c) + word.slice(i + 1);
if (words.delete(nxt)) next.push(nxt);
}
}
}
queue = next;
length++;
}
return 0;
}Word Ladder in C
static bool oneApart(const char* a, const char* b) {
int diff = 0;
for (; *a; a++, b++) if (*a != *b && ++diff > 1) return false;
return diff == 1;
}
int ladderLength(char* beginWord, char* endWord, char** wordList, int wordListSize) {
int end = -1;
for (int i = 0; i < wordListSize; i++) if (!strcmp(wordList[i], endWord)) end = i;
if (end == -1) return 0;
bool* seen = calloc(wordListSize, sizeof(bool));
char** queue = malloc((wordListSize + 1) * sizeof(char*));
int head = 0, tail = 0, length = 1;
queue[tail++] = beginWord;
while (head < tail) {
for (int size = tail - head; size > 0; size--) {
char* word = queue[head++];
if (!strcmp(word, endWord)) { free(seen); free(queue); return length; }
for (int j = 0; j < wordListSize; j++) {
if (!seen[j] && oneApart(word, wordList[j])) {
seen[j] = true;
queue[tail++] = wordList[j];
}
}
}
length++;
}
free(seen);
free(queue);
return 0;
}Edge Cases & Common Mistakes
- endWord not in the list: return 0 before searching.
- Counting edges instead of words: the answer counts words, so
beginWordalone has length 1. - Marking visited on pop instead of on push: the same word can be queued many times in one level; remove it from the set when it is queued.
- Using DFS: DFS finds a ladder, not necessarily the shortest; BFS levels guarantee the minimum.
Summary
Words are nodes and one-letter changes are edges, so the shortest ladder is a BFS shortest path. Queue beginWord, expand each level by trying every letter at every position, remove words from the set as they are queued, and return the level count when endWord is reached, or 0.
More practice: DSA interview questions with answers · patterns cheat sheet
