Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the length of the shortest transformation from a start word to an end word, changing one letter at a time, every intermediate word being in the dictionary.

Problem: Find the length of the shortest transformation from a start word to an end word, changing one letter at a time, every intermediate word being in the dictionary.
from collections import deque
def ladder(a, z, words):
    words = set(words)
    if z not in words: return 0
    q, seen = deque([(a, 1)]), {a}
    while q:
        w, d = q.popleft()
        if w == z: return d
        for i in range(len(w)):
            for ch in 'abcdefghijklmnopqrstuvwxyz':
                nw = w[:i] + ch + w[i + 1:]
                if nw in words and nw not in seen:
                    seen.add(nw); q.append((nw, d + 1))
    return 0
print(ladder("cold", "warm", ["cord", "card", "ward", "warm", "word", "worm", "wore", "core"]))
What is printed?
  1. A. 5
  2. B. 4
  3. C. 6
  4. D. 0

Correct answer: A. 5

BFS on implicit word graph: cold → cord → card → ward → warm (or cord → word → worm → warm), 5 words including both ends. Returning the number of changes (4) instead of words is the usual off-by-one. Each word tries 26·L neighbours: O(N · 26 · L²) with string slicing.

More Coding Interview Problems questions

Exams that ask this topic