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?- A. 5
- B. 4
- C. 6
- 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
- Problem: Determine whether a graph can be coloured with two colours so that no edge joins equal colours (bipartite). python from…
- Problem: Count the number of shortest paths (fewest edges) from node 0 to node n − 1 in an unweighted graph. python from collections…
- Problem: In a grid, 0 is open and 1 is a wall. Find the shortest path length (in cells) from the top-left to the bottom-right moving in 8…
- Problem: Each cell of a grid holds 0 (empty) or 1. Return a grid of the distance from each cell to its nearest 0. python from collections…
- Problem: A city grid has V = 10⁵ junctions; every road takes either 0 minutes (flyover) or 1 minute. What is the most efficient way to get…
- Problem: A graph of flights has prices; find the cheapest price from src to dst using at most k stops (Bellman–Ford limited to k + 1…