Minimum Steps in Word Ladder
Trees & GraphsAuto-graded · 23 test casesLast updated
Tests BFS on an implicit graph with efficient neighbor generation using wildcard pattern indexing.
You are given two words source and target of equal length, along with a list of valid words. In a single step, you may change exactly one letter in your current word to produce a new word that must appear in the valid word list.
Determine the minimum number of steps required to transform source into target. If no such transformation exists, return -1.
Rules:
- Only words of the same length as
sourceandtargetare considered valid. - The
targetword must be present in the valid word list. - The
sourceword does not need to be in the list initially. - If
sourceandtargetare identical, return0regardless of whether they appear in the word list. - If
sourceandtargethave different lengths, return-1.
Constraints:
1 <= len(source) <= 101 <= len(target) <= 100 <= len(words) <= 5000- All words consist of lowercase English letters
source != ""andtarget != ""
Examples
Example 1
Input: min_word_ladder_steps('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log', 'cog'])
Output: 4
Example 2
Input: min_word_ladder_steps('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log'])
Output: -1
Example 3
Input: min_word_ladder_steps('same', 'same', [])
Output: 0
Hints
Hint 1
Model this as a shortest path problem where each word is a node and edges connect words differing by one letter.
Hint 2
Use BFS to explore words level by level, guaranteeing the first path found to the target is shortest.
Hint 3
Generate neighbors efficiently by creating wildcard patterns (e.g., 'h*t' matches 'hot', 'hit') and grouping words by shared patterns.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem asks for the shortest transformation sequence between two words, where each step changes exactly one letter and produces a valid word. This is a shortest path problem on an unweighted graph where nodes are words and edges connect words differing by a single character.
Since all edges have equal weight, breadth-first search (BFS) naturally finds the shortest path. BFS explores words in order of increasing distance from the source, so the first time we reach the target, we have found an optimal solution.
The challenge is efficiently finding neighbors. Comparing each word against all others costs O(N·L) per word, where N is the dictionary size and L is word length. Instead, we use wildcard pattern indexing:
- For each word, generate L patterns by replacing each position with
*. For example,"hot"produces"*ot","h*t", and"ho*". - Group words into buckets by pattern. Two words sharing a pattern differ by exactly one letter at the wildcard position.
- During BFS, look up a word's patterns to find all neighbors in O(L) bucket lookups.
An important optimization: after expanding a pattern bucket during BFS, we clear it. Any word in that bucket has already been discovered at distance d+1 or less, so re-expanding the same bucket from another node at distance d or greater can never improve any path.
Edge cases handled:
- If source equals target, return 0 immediately
- Filter words to match source/target length
- Verify target exists in the valid word list
- Add source to the word set (it may not be in the original list)
- Return -1 if the queue empties without finding target
Complexity
Let N be the number of words (after filtering by length) and L be the word length.
- Time: Building pattern buckets takes O(N·L²) since we create L patterns of length L for each of N words. BFS visits each word once, generating L patterns per word at O(L) each, for O(N·L²). Total bucket entries scanned is bounded by N·L due to clearing. Overall: O(N·L²).
- Space: The bucket map stores N·L patterns, each of length L, for O(N·L²). The queue and visited set add O(N·L).
Solution
from collections import defaultdict, deque
from typing import List
def min_word_ladder_steps(source: str, target: str, words: List[str]) -> int:
if source == target:
return 0
if len(source) != len(target):
return -1
word_set = {word for word in words if len(word) == len(source)}
if target not in word_set:
return -1
word_set.add(source)
buckets = defaultdict(list)
for word in word_set:
for i in range(len(word)):
buckets[word[:i] + "*" + word[i + 1:]].append(word)
queue = deque([(source, 0)])
visited = {source}
while queue:
word, distance = queue.popleft()
for i in range(len(word)):
pattern = word[:i] + "*" + word[i + 1:]
for neighbor in buckets[pattern]:
if neighbor == target:
return distance + 1
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, distance + 1))
buckets[pattern].clear()
return -1