ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

What is printed?
from collections import deque
def ladder(begin, end, words):
    S = set(words)
    q = deque([(begin, 1)])
    seen = {begin}
    while q:
        w, d = q.popleft()
        if w == end:
            return d
        for i in range(len(w)):
            for ch in 'abcdefghijklmnopqrstuvwxyz':
                nw = w[:i] + ch + w[i+1:]
                if nw in S and nw not in seen:
                    seen.add(nw)
                    q.append((nw, d + 1))
    return 0
print(ladder('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log', 'cog']))
  1. A. 5
  2. B. 4
  3. C. 3
  4. D. 0

Correct answer: A. 5

BFS over one-letter changes finds the path hit, hot, dot, dog, cog. The counter starts at 1 for the first word, so the path length is 5.

More Python Programming questions

Exams that ask this topic