DSA AnimatorDSA animations
Word Ladder LC #127 Hard BFS · Implicit Graph
Problem

Given beginWord, endWord and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, where each step changes exactly one letter and every intermediate word must be in wordList. Return 0 if no sequence exists.

Example 1
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5 (hit → hot → dot → dog → cog)
Example 2
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0 ("cog" is not in the list)
Constraints: 1 ≤ beginWord.length ≤ 10  |  all words have the same length  |  wordList.length ≤ 5000  |  lowercase letters
🪜 Words
🔎 Neighbour search appears here
the one letter that changed word being expanded newly discovered 🔢 badge = BFS level (words so far)
Variables
current word
level
queue size
seen
💡 Step Logic
Press ▶ Play or Next to begin.
Ready
0 / 0
Pick an example and press Play.
Algorithm
1
If endWord isn't in the list, return 0. Put the list in a HashSet
2
BFS queue starts with beginWord at level 1
3
Pop a word; at each position try 'a'…'z' ("h?t")
4
If the new word is endWord → return level + 1 🎉
5
If it's an unseen dictionary word → mark seen, enqueue at level + 1
6
Queue empty → no ladder, return 0
Time
O(N · L · 26)
Space
O(N · L)
🧠 Why BFS, not DFS?

DFS may wander down a long ladder first and still has to explore everything to be sure it's the shortest. BFS explores in rings of equal distance, so the first time it touches endWord is the minimum. Mark words seen when you enqueue them (not when you pop) so no word is queued twice. For big inputs, bidirectional BFS from both ends meets in the middle and is much faster.

⚠️ Edge cases

endWord not in the list → 0 immediately. beginWord doesn't have to be in the list. The answer counts words in the ladder, not moves (hit→hot→dot→dog→cog = 5). Several shortest ladders can exist; BFS returns the length, and all of them are equally short.