Crack the Code: Master the Word Ladder Leetcode Challenge

Aruvansh
3 min readJul 26, 2023

--

In a word ladder problem, you are given two words — a starting word and an ending word. The goal is to transform the starting word into the ending word by changing one letter at a time. At each step, you can only change one letter, and the new word formed must be a valid word from the given word list.

For example, let’s say we have the starting word “hit” and the ending word “cog,” and we have the word list [“hot”, “dot”, “dog”, “lot”, “log”, “cog”]. The word ladder solution in this case would be: “hit” -> “hot” -> “dot” -> “dog” -> “cog.”

The idea is to use a breadth-first search (BFS) approach to explore all possible word transformations while keeping track of the shortest path to reach the ending word.

Here’s a simple explanation of how to approach the problem along with the code:

  1. Since the difference between characters should be at most one we need to create a way in which words are connected to each other. What better way than creating a type of a graph. e.g. “hit” should be in linked to “hot”, “dot”, “lot”.
  2. Since we have finalized the data structure, the question comes on how should we implement it. As we see it should just differ by one then we should create a wildcard character at every idx one by one and put in a map. For instance “hot” will change to “*ot”, “h*t”, “ho*”.
  combinations = defaultdict(list)
for word in wordList:
for i in range(0,len(word)):
tmp = word[:i] + "*" + word[i + 1:]
combinations[tmp].append(word)

#Complexity: O(N * M) [M --> len(word) and N --> len(wordList)]
Output: When you print combinations (you see how the wildcard charcter helped us achieved step one)

defaultdict(<class 'list'>, {'*ot': ['hot', 'dot', 'lot'], 'h*t': ['hot'], 'ho*': ['hot'], 'd*t': ['dot'], 'do*': ['dot', 'dog'], '*og': ['dog', 'log', 'cog'], 'd*g': ['dog'], 'l*t': ['lot'], 'lo*': ['lot', 'log'], 'l*g': ['log'], 'c*g': ['cog'], 'co*': ['cog']})

3. Now is the easy part, since the graph is created perform a simple bfs to get the answer. Detailed steps are provided below:

        queue = [(beginWord,1)]
visited = set([beginWord])
while queue:
curr,level = queue.pop(0)
if curr == endWord:
return level
for i in range(len(curr)):
tmp = curr[:i] + "*" + curr[i + 1:]
for w in combinations[tmp]:
if w in visited:
continue
queue.append((w,level+1))
visited.add(w)

#Complexity: Generic BFS -> O(V+E)

a. Start with the starting word and put it in a queue.

b. Keep a visited set to keep track of all the visited words.

c. While the queue is not empty, dequeue a word.

d. Check if the word == endWord if yes return the level

e. If not iterate over the graph and append to the queue

f. If you finish exploring all possible transformations and haven’t found the ending word, it means there is no word ladder possible from the starting word to the ending word.

Pointers : Remember to keep track of visited words to avoid cycles and unnecessary reprocessing. Also, with this data structure the lookup is reduced to 0(1)

I hope this simple explanation helps you understand how to solve the word ladder problem on LeetCode! Good luck!

--

--

Aruvansh

Software developer passionate about algorithm design, Angular, RxJS, and geopolitics. Stay updated on the latest tech trends. Coding my way to innovation! 🚀