Word ladder
Shortest chain from one word to another, changing one letter per step, always through words in the list. BFS over a graph of words.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Picture every word as a node, with an edge between two words that differ in exactly one letter. The shortest transformation sequence is then just the shortest path in that graph, found with ordinary layer-by-layer BFS: each layer is one more word in the chain.
Code
public static int LadderLength(string begin, string end, HashSet<string> wordList) {
var queue = new Queue<string>();
queue.Enqueue(begin);
var seen = new HashSet<string> { begin };
int steps = 1;
while (queue.Count > 0) {
int size = queue.Count;
for (int i = 0; i < size; i++) {
string word = queue.Dequeue();
if (word == end) return steps;
foreach (string next in Neighbours(word, wordList))
if (seen.Add(next)) queue.Enqueue(next);
}
steps++;
}
return 0; // end is unreachable
}static int ladderLength(String begin, String end, Set<String> wordList) {
Queue<String> queue = new ArrayDeque<>();
queue.offer(begin);
Set<String> seen = new HashSet<>(); seen.add(begin);
int steps = 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String word = queue.poll();
if (word.equals(end)) return steps;
for (String next : neighbours(word, wordList))
if (seen.add(next)) queue.offer(next);
}
steps++;
}
return 0; // end is unreachable
}int ladderLength(const string& begin, const string& end, const unordered_set<string>& wordList) {
queue<string> q;
q.push(begin);
unordered_set<string> seen{begin};
int steps = 1;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
string word = q.front(); q.pop();
if (word == end) return steps;
for (const string& next : neighbours(word, wordList))
if (seen.insert(next).second) q.push(next);
}
steps++;
}
return 0; // end is unreachable
}from collections import deque
def ladder_length(begin: str, end: str, word_list: set[str]) -> int:
queue = deque()
queue.append(begin)
seen = {begin}
steps = 1
while queue:
for _ in range(len(queue)):
word = queue.popleft()
if word == end: return steps
for nxt in neighbours(word, word_list):
if nxt not in seen: seen.add(nxt); queue.append(nxt)
steps += 1
return 0 # end is unreachableTips
- Build the "changes one letter" neighbours by trying every position and every other letter, keeping only results that are in the word list.
- Precomputing a word -> neighbours map once is far faster than rescanning the whole list for every word during the search.
In the .NET library
Interview answers often quote O(N × L²) time: N words, each compared or mutated in roughly L positions times L alphabet tries (26) times length-L string work; a two-ended BFS from both begin and end halves the frontier in practice.