AlgoInsight

DSA problem

Word Ladder

HardBreadth First Search (BFS)Pattern: Breadth First Search (BFS)top75AmazonGoogleMicrosoftMetaLinkedIn

Given two words beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.

A transformation sequence is a list of words s_0 = beginWord, s_1, ..., s_k = endWord such that every adjacent pair s_i, s_{i+1} differs in exactly one letter and every s_i for i >= 1 is in wordList. The number of words in the sequence equals k + 1.

The straightforward modelling builds a graph where each dictionary word is a node and two nodes are connected if they differ in exactly one letter, then BFS from beginWord. But naively comparing every pair of words to build edges costs O(N^2 * L) where N is the dictionary size and L the word length — too slow for the constraints.

The classic optimisation is the wildcard pattern map. For every word, generate L patterns by replacing each character in turn with * (e.g. "hit" -> "*it", "h*t", "hi*"). Words sharing a pattern differ in exactly one letter at that position, so BFS can use the patterns to find neighbours in O(L) per word instead of scanning the whole dictionary. Total time becomes O(N * L^2) and space O(N * L^2).

BFS proceeds level by level from beginWord. When endWord is dequeued, the current level + 1 is the answer (sequence length is hops + 1). Mark words visited at enqueue time to avoid revisits and erase exhausted patterns from the map to avoid redundant work.

Examples

Example 1
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: One shortest sequence is "hit" -> "hot" -> "dot" -> "dog" -> "cog", which has 5 words.
Example 2
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: endWord is not in the dictionary, so no valid transformation exists.
Example 3
Input: beginWord = "a", endWord = "c", wordList = ["a","b","c"]
Output: 2
Explanation: "a" -> "c" differs by one letter and "c" is in the list, so the sequence has 2 words.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bfsgraphshortest-pathstringhash-table

Browse all DSA problems