Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find number of steps required to change one word to another in Python
Suppose we have a list of words called dictionary and we have another two strings start and end. We want to reach from start to end by changing one character at a time and each resulting word should also be in the dictionary. Words are case-sensitive. So we have to find the minimum number of steps it would take to reach at the end. If it is not possible then return -1.
So, if the input is like dictionary = ["may", "ray", "rat"] start = "rat" end = "may", then the output will be 3, as we can select this path: ["rat", "ray", "may"].
Algorithm
To solve this, we will follow these steps ?
dictionary := a new set with all unique elements present in dictionary
q = a double ended queue with a pair (start, 1)
while q is not empty, do
(word, distance) := left element of q, and delete the left element
if word is same as end, then
return distance
for i in range 0 to size of word - 1, do
for each character c in "abcdefghijklmnopqrstuvwxyz", do
next_word := word[from index 0 to i - 1] concatenate c concatenate word[from index (i + 1) to end]
if next_word is in dictionary, then
delete next_word from dictionary
insert (next_word, distance + 1) at the end of q
return -1
Implementation
Let us see the following implementation to get better understanding ?
from collections import deque
class Solution:
def solve(self, dictionary, start, end):
dictionary = set(dictionary)
q = deque([(start, 1)])
while q:
word, distance = q.popleft()
if word == end:
return distance
for i in range(len(word)):
for c in "abcdefghijklmnopqrstuvwxyz":
next_word = word[:i] + c + word[i + 1:]
if next_word in dictionary:
dictionary.remove(next_word)
q.append((next_word, distance + 1))
return -1
# Test the solution
ob = Solution()
dictionary = ["may", "ray", "rat"]
start = "rat"
end = "may"
print(ob.solve(dictionary, start, end))
3
How It Works
This solution uses Breadth-First Search (BFS) to find the shortest path. The algorithm works as follows:
- Convert the dictionary to a set for O(1) lookup operations
- Use a queue to explore words level by level (ensuring minimum steps)
- For each word, try changing every character to all 26 possible letters
- If the new word exists in dictionary, add it to queue and remove from dictionary
- Continue until we reach the end word or exhaust all possibilities
Alternative Example
from collections import deque
def word_ladder_steps(dictionary, start, end):
if end not in dictionary:
return -1
word_set = set(dictionary)
queue = deque([(start, 1)])
while queue:
current_word, steps = queue.popleft()
if current_word == end:
return steps
# Try changing each character
for i in range(len(current_word)):
for char in 'abcdefghijklmnopqrstuvwxyz':
if char != current_word[i]:
new_word = current_word[:i] + char + current_word[i+1:]
if new_word in word_set:
word_set.remove(new_word)
queue.append((new_word, steps + 1))
return -1
# Example 1
dictionary1 = ["hot", "dot", "dog", "lot", "log", "cog"]
print(word_ladder_steps(dictionary1, "hit", "cog"))
# Example 2
dictionary2 = ["may", "ray", "rat"]
print(word_ladder_steps(dictionary2, "rat", "may"))
5 3
Conclusion
This problem is solved using BFS to find the shortest transformation sequence. The key insight is treating each word as a node and valid transformations as edges, ensuring we find the minimum number of steps required.
