Word Ladder
Problem Statement
You are given two words, beginWord and endWord, and a list of words, wordList. A step changes exactly one letter of a word.
A word ladder is a sequence of words that starts at beginWord and ends at endWord. Each word differs from the word before it by one letter, and every word after beginWord must be in wordList. The beginWord does not have to be in the list.
Return the number of words in the shortest such sequence, counting beginWord and endWord. Counting words is not the same as counting steps: a sequence of 5 words has 4 steps. If no sequence exists, return 0.
beginWord and endWord, two words of the same length. wordList, the words that may be used.
The number of words in the shortest sequence, or 0 if there is none.
One shortest sequence is hit → hot → dot → dog → cog. It has 5 words, so the answer is 5 (not the 4 steps between them).
cog is not in the list, so no sequence can end on it.
aa → ab → bb. Three words, two steps.
- • All words have the same length, from 1 to 10 letters.
- • The list has between 1 and 5000 words, and every word in it is unique.
- • All words use only the lowercase letters a to z.
- • beginWord and endWord are different words.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Compare every pair of words to build the graph, then run BFS from beginWord
BFS from beginWord; from each word, try every one-letter change and look it up in a hash set
First build the graph. Check every pair of words, and connect a pair when they differ in exactly one letter. Then run BFS from beginWord, counting words. The count when endWord is reached is the answer.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.