Word Ladder
You are given two words:
beginWord
endWord
and a dictionary of words called wordList.
Find the length of the shortest transformation sequence from beginWord to endWord.
A transformation is valid when:
- Only one character can be changed at a time.
- Every intermediate word must exist in wordList.
If no transformation is possible, return:
-1
Example
beginWord = "hit"
endWord = "cog"
wordList =
["hot","dot","dog","lot","log","cog"]
One shortest transformation is:
hit
↓
hot
↓
dot
↓
dog
↓
cog
The sequence contains 5 words.
Therefore:
5
Main Idea
This is a BFS + HashSet problem.
Treat every word as a node in a graph.
Two words are connected if they differ by exactly one character.
For example:
hit → hot
because only the third character changes:
h i t
h o t
Since every transformation costs exactly 1, BFS finds the shortest transformation.
BFS Process
Start with:
hit
Generate all possible one-character transformations:
ait
bit
cit
...
hot
...
If a generated word exists in the dictionary, add it to the queue.
Continue until:
endWord
is reached.
Example 1
Input
hit cog 6 hot dot dog lot log cog
Output
5
Explanation
The shortest transformation is:
hit
↓
hot
↓
dot
↓
dog
↓
cog
The sequence contains:
5 words
Therefore the answer is:
5
Example 2
Input
hit cog 5 hot dot dog lot log
Output
0
Explanation
cog is not present in the wordList.
Therefore, no valid transformation can reach cog.
So the answer is:
0
Constraints
Hints:
Hint 1
Think of every word as a node in a graph.
Hint 2
Two words are connected when they differ by exactly one character.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 16, 2026
Last updated
Aug 17, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output