127. Word Ladder
Hard NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Graphs
- Time
- O(N * M * 26)
- Space
- O(N)
Standard Solution (C++)
SummaryGiven a start word, an end word, and a dictionary of valid words, find the shortest transformation sequence where each step changes exactly one letter and every intermediate word must exist in the dictionary — returning the number of words in the shortest path, or 0 if none exists.
Approach
- Use BFS from
beginWord, exploring all one-letter mutations at each level; BFS guarantees the first timeendWordis reached it is via the shortest path. - For each word dequeued, iterate over every character position and try all 26 substitutions; if the mutated word is in the unvisited dictionary set, enqueue it and mark it visited (erase from the set) immediately to prevent redundant work.
- The level counter is incremented once per BFS frontier expansion, so when
endWordis found during mutation the current level plus one equals the sequence length (counting both endpoints). - Early-exit if
endWordis not in the word list at all.
#include <string>
#include <vector>
#include <unordered_set>
#include <queue>
using namespace std;
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
// Build a hash set for O(1) membership checks; also serves as visited tracker.
unordered_set<string> available(wordList.begin(), wordList.end());
// If the target isn't in the dictionary, transformation is impossible.
if (!available.count(endWord)) return 0;
queue<string> bfsQueue;
bfsQueue.push(beginWord);
int steps = 1; // beginWord itself counts as step 1
while (!bfsQueue.empty()) {
int levelSize = static_cast<int>(bfsQueue.size());
// Process all nodes at the current BFS depth.
for (int i = 0; i < levelSize; ++i) {
string word = bfsQueue.front();
bfsQueue.pop();
// Try mutating every character position.
for (int pos = 0; pos < static_cast<int>(word.size()); ++pos) {
char original = word[pos];
for (char c = 'a'; c <= 'z'; ++c) {
if (c == original) continue;
word[pos] = c;
if (word == endWord) return steps + 1;
if (available.count(word)) {
// Mark visited by removing from the set before enqueuing.
available.erase(word);
bfsQueue.push(word);
}
word[pos] = original; // restore
}
}
}
++steps;
}
return 0; // endWord unreachable
}
};
Time O(N * M * 26) where N is the number of words in the word list and M is the length of each word Space O(N * M) for the hash set and BFS queue storing up to N words of length M
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
int len=wordList.size();
unordered_set<string> notVisited(wordList.begin(), wordList.end());
if(!notVisited.count(endWord)){
return 0;
}
queue<string> q;
q.push(beginWord);
int dist=0;
while(!q.empty()){
++dist;
int qlen=q.size();
for(int i=0; i<qlen; ++i){
string cur=q.front();
q.pop();
if(cur==endWord){
return dist;
}
for(int i=0; i<cur.length(); ++i){
char originalChar=cur[i];
for(int j=0; j<26; ++j){
cur[i]='a'+j;
if(notVisited.count(cur)){
q.push(cur);
notVisited.erase(cur);
}
}
cur[i]=originalChar;
}
}
}
return 0;
}
};
// Time Complexity: O(N * M * 26), N is the number of words in wordList, M is the length of each word
// Space Complexity: O(N) Time O(N * M * 26) Space O(N)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.