Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:
si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.sk == endWordGiven two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] Explanation: There are 2 shortest transformation sequences: "hit" -> "hot" -> "dot" -> "dog" -> "cog" "hit" -> "hot" -> "lot" -> "log" -> "cog"
Example 2:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: [] Explanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
Constraints:
1 <= beginWord.length <= 5endWord.length == beginWord.length1 <= wordList.length <= 500wordList[i].length == beginWord.lengthbeginWord, endWord, and wordList[i] consist of lowercase English letters.beginWord != endWordwordList are unique.105.Problem summary: A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that: Every adjacent pair of words differs by a single letter. Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList. sk == endWord Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Backtracking
"hit" "cog" ["hot","dot","dog","lot","log","cog"]
"hit" "cog" ["hot","dot","dog","lot","log"]
word-ladder)groups-of-strings)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #126: Word Ladder II
class Solution {
private List<List<String>> ans;
private Map<String, Set<String>> prev;
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
ans = new ArrayList<>();
Set<String> words = new HashSet<>(wordList);
if (!words.contains(endWord)) {
return ans;
}
words.remove(beginWord);
Map<String, Integer> dist = new HashMap<>();
dist.put(beginWord, 0);
prev = new HashMap<>();
Queue<String> q = new ArrayDeque<>();
q.offer(beginWord);
boolean found = false;
int step = 0;
while (!q.isEmpty() && !found) {
++step;
for (int i = q.size(); i > 0; --i) {
String p = q.poll();
char[] chars = p.toCharArray();
for (int j = 0; j < chars.length; ++j) {
char ch = chars[j];
for (char k = 'a'; k <= 'z'; ++k) {
chars[j] = k;
String t = new String(chars);
if (dist.getOrDefault(t, 0) == step) {
prev.get(t).add(p);
}
if (!words.contains(t)) {
continue;
}
prev.computeIfAbsent(t, key -> new HashSet<>()).add(p);
words.remove(t);
q.offer(t);
dist.put(t, step);
if (endWord.equals(t)) {
found = true;
}
}
chars[j] = ch;
}
}
}
if (found) {
Deque<String> path = new ArrayDeque<>();
path.add(endWord);
dfs(path, beginWord, endWord);
}
return ans;
}
private void dfs(Deque<String> path, String beginWord, String cur) {
if (cur.equals(beginWord)) {
ans.add(new ArrayList<>(path));
return;
}
for (String precursor : prev.get(cur)) {
path.addFirst(precursor);
dfs(path, beginWord, precursor);
path.removeFirst();
}
}
}
// Accepted solution for LeetCode #126: Word Ladder II
func findLadders(beginWord string, endWord string, wordList []string) [][]string {
var ans [][]string
words := make(map[string]bool)
for _, word := range wordList {
words[word] = true
}
if !words[endWord] {
return ans
}
words[beginWord] = false
dist := map[string]int{beginWord: 0}
prev := map[string]map[string]bool{}
q := []string{beginWord}
found := false
step := 0
for len(q) > 0 && !found {
step++
for i := len(q); i > 0; i-- {
p := q[0]
q = q[1:]
chars := []byte(p)
for j := 0; j < len(chars); j++ {
ch := chars[j]
for k := 'a'; k <= 'z'; k++ {
chars[j] = byte(k)
t := string(chars)
if v, ok := dist[t]; ok {
if v == step {
prev[t][p] = true
}
}
if !words[t] {
continue
}
if len(prev[t]) == 0 {
prev[t] = make(map[string]bool)
}
prev[t][p] = true
words[t] = false
q = append(q, t)
dist[t] = step
if endWord == t {
found = true
}
}
chars[j] = ch
}
}
}
var dfs func(path []string, begin, cur string)
dfs = func(path []string, begin, cur string) {
if cur == beginWord {
cp := make([]string, len(path))
copy(cp, path)
ans = append(ans, cp)
return
}
for k := range prev[cur] {
path = append([]string{k}, path...)
dfs(path, beginWord, k)
path = path[1:]
}
}
if found {
path := []string{endWord}
dfs(path, beginWord, endWord)
}
return ans
}
# Accepted solution for LeetCode #126: Word Ladder II
class Solution:
def findLadders(
self, beginWord: str, endWord: str, wordList: List[str]
) -> List[List[str]]:
def dfs(path, cur):
if cur == beginWord:
ans.append(path[::-1])
return
for precursor in prev[cur]:
path.append(precursor)
dfs(path, precursor)
path.pop()
ans = []
words = set(wordList)
if endWord not in words:
return ans
words.discard(beginWord)
dist = {beginWord: 0}
prev = defaultdict(set)
q = deque([beginWord])
found = False
step = 0
while q and not found:
step += 1
for i in range(len(q), 0, -1):
p = q.popleft()
s = list(p)
for i in range(len(s)):
ch = s[i]
for j in range(26):
s[i] = chr(ord('a') + j)
t = ''.join(s)
if dist.get(t, 0) == step:
prev[t].add(p)
if t not in words:
continue
prev[t].add(p)
words.discard(t)
q.append(t)
dist[t] = step
if endWord == t:
found = True
s[i] = ch
if found:
path = [endWord]
dfs(path, endWord)
return ans
// Accepted solution for LeetCode #126: Word Ladder II
struct Solution;
use std::collections::HashMap;
use std::collections::HashSet;
use std::iter::FromIterator;
impl Solution {
fn find_ladders(
begin_word: String,
end_word: String,
word_list: Vec<String>,
) -> Vec<Vec<String>> {
let mut dict: HashSet<String> = HashSet::new();
for word in word_list {
dict.insert(word);
}
if !dict.contains(&end_word) {
return vec![];
}
let set1: HashSet<String> = HashSet::from_iter(vec![begin_word.to_string()]);
let set2: HashSet<String> = HashSet::from_iter(vec![end_word.to_string()]);
let mut map: HashMap<String, HashSet<String>> = HashMap::new();
Self::bfs(set1, set2, false, &mut map, &mut dict);
let mut path = vec![begin_word.to_string()];
let mut res = vec![];
Self::dfs(&begin_word, &mut path, &mut res, &map, &end_word);
res
}
fn bfs(
set1: HashSet<String>,
set2: HashSet<String>,
flipped: bool,
map: &mut HashMap<String, HashSet<String>>,
dict: &mut HashSet<String>,
) {
if set1.is_empty() {
return;
}
if set1.len() > set2.len() {
Self::bfs(set2, set1, !flipped, map, dict);
return;
}
for s in set1.iter() {
dict.remove(s);
}
for s in set2.iter() {
dict.remove(s);
}
let mut next: HashSet<String> = HashSet::new();
let mut done = false;
for word in set1.iter() {
for next_word in Self::connected_words(&word.to_string()) {
let key = if flipped {
next_word.to_string()
} else {
word.to_string()
};
let value = if flipped {
word.to_string()
} else {
next_word.to_string()
};
if set2.contains(&next_word) {
done = true;
map.entry(key).or_default().insert(value);
} else if dict.contains(&next_word) {
next.insert(next_word);
map.entry(key).or_default().insert(value);
}
}
}
if !done {
Self::bfs(set2, next, !flipped, map, dict);
}
}
fn dfs(
start: &str,
path: &mut Vec<String>,
all: &mut Vec<Vec<String>>,
map: &HashMap<String, HashSet<String>>,
end: &str,
) {
if start == end {
all.push(path.to_vec());
} else {
if let Some(nei) = map.get(start) {
for next in nei.iter() {
path.push(next.to_string());
Self::dfs(next, path, all, map, end);
path.pop();
}
}
}
}
fn connected_words(word: &str) -> Vec<String> {
let n = word.len();
let mut res = vec![];
for i in 0..n {
let mut s: Vec<char> = word.chars().collect();
for j in 0..26 {
let c = (b'a' + j as u8) as char;
s[i] = c;
let new_word: String = s.iter().collect();
res.push(new_word);
}
}
res
}
}
#[test]
fn test() {
let begin_word = "hit".to_string();
let end_word = "cog".to_string();
let word_list = vec_string!["hot", "dot", "dog", "lot", "log", "cog"];
let mut res = vec_vec_string![
["hit", "hot", "dot", "dog", "cog"],
["hit", "hot", "lot", "log", "cog"]
];
let mut ans = Solution::find_ladders(begin_word, end_word, word_list);
res.sort();
ans.sort();
assert_eq!(ans, res);
let begin_word = "hit".to_string();
let end_word = "cog".to_string();
let word_list = vec_string!["hot", "dot", "dog", "lot", "log"];
let res = vec_vec_string![];
assert_eq!(Solution::find_ladders(begin_word, end_word, word_list), res);
let begin_word = "a".to_string();
let end_word = "c".to_string();
let word_list = vec_string!["a", "b", "c"];
let mut res = vec_vec_string![["a", "c"]];
let mut ans = Solution::find_ladders(begin_word, end_word, word_list);
res.sort();
ans.sort();
assert_eq!(ans, res);
}
// Accepted solution for LeetCode #126: Word Ladder II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #126: Word Ladder II
// class Solution {
// private List<List<String>> ans;
// private Map<String, Set<String>> prev;
//
// public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
// ans = new ArrayList<>();
// Set<String> words = new HashSet<>(wordList);
// if (!words.contains(endWord)) {
// return ans;
// }
// words.remove(beginWord);
// Map<String, Integer> dist = new HashMap<>();
// dist.put(beginWord, 0);
// prev = new HashMap<>();
// Queue<String> q = new ArrayDeque<>();
// q.offer(beginWord);
// boolean found = false;
// int step = 0;
// while (!q.isEmpty() && !found) {
// ++step;
// for (int i = q.size(); i > 0; --i) {
// String p = q.poll();
// char[] chars = p.toCharArray();
// for (int j = 0; j < chars.length; ++j) {
// char ch = chars[j];
// for (char k = 'a'; k <= 'z'; ++k) {
// chars[j] = k;
// String t = new String(chars);
// if (dist.getOrDefault(t, 0) == step) {
// prev.get(t).add(p);
// }
// if (!words.contains(t)) {
// continue;
// }
// prev.computeIfAbsent(t, key -> new HashSet<>()).add(p);
// words.remove(t);
// q.offer(t);
// dist.put(t, step);
// if (endWord.equals(t)) {
// found = true;
// }
// }
// chars[j] = ch;
// }
// }
// }
// if (found) {
// Deque<String> path = new ArrayDeque<>();
// path.add(endWord);
// dfs(path, beginWord, endWord);
// }
// return ans;
// }
//
// private void dfs(Deque<String> path, String beginWord, String cur) {
// if (cur.equals(beginWord)) {
// ans.add(new ArrayList<>(path));
// return;
// }
// for (String precursor : prev.get(cur)) {
// path.addFirst(precursor);
// dfs(path, beginWord, precursor);
// path.removeFirst();
// }
// }
// }
Use this to step through a reusable interview workflow for this problem.
Generate every possible combination without any filtering. At each of n positions we choose from up to n options, giving nⁿ total candidates. Each candidate takes O(n) to validate. No pruning means we waste time on clearly invalid partial solutions.
Backtracking explores a decision tree, but prunes branches that violate constraints early. Worst case is still factorial or exponential, but pruning dramatically reduces the constant factor in practice. Space is the recursion depth (usually O(n) for n-level decisions).
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.