Problem
Change a word into another by changing only only one character at a time. All intermediate words should be contained in a dictionary.
Examples
Example 1:
|
|
Similar problems
Word Ladder 1 - Get Ladder Length Word Ladder 2 - Get all the ladders Word Ladder - Get shortest ladder Word Ladder - Get shortest ladder by changing, adding or removing one letter at a time
Solution
This problem is pretty simple if we can choose a proper data structure. Here is the second part of the problem - Word Ladder 1 - Get Ladder Length.
Method 1 - BFS
Example
Given a dictionary {"DOG", "COT", "COG", "FOG", "DOT"}
, start word "FOG"
, and target word "COT"
.
From "FOG"
, we can generate new words by changing each letter to any other letter from ‘A’ to ‘Z’, but only keep those present in the dictionary. Here, "COG"
and "DOG"
are valid next steps.
If any transformed word matches the target, we’ve succeeded. Otherwise, we repeat the process for each valid transformation. If no sequence leads to the target, the search fails. For instance, "FOG"
→ "COG"
→ "COT"
is a valid path.
This problem naturally fits a breadth-first search (BFS) approach, using a queue to explore all possible transformations level by level.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- 🧺 Space complexity:
O(n)