Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: A lock has 4 wheels of digits 0–9; one move turns one wheel by ±1 (wrapping 9↔0). Starting at '0000', find the fewest moves to reach the target without ever showing a dead-end code.

Problem: A lock has 4 wheels of digits 0–9; one move turns one wheel by ±1 (wrapping 9↔0). Starting at '0000', find the fewest moves to reach the target without ever showing a dead-end code.
from collections import deque
def open_lock(dead, target):
    dead = set(dead)
    q, seen = deque([("0000", 0)]), {"0000"}
    while q:
        s, d = q.popleft()
        if s == target: return d
        for i in range(4):
            for step in (1, -1):
                t = s[:i] + str((int(s[i]) + step) % 10) + s[i+1:]
                if t not in seen and t not in dead:
                    seen.add(t); q.append((t, d + 1))
    return -1
print(open_lock(["0001", "0010"], "0011"))
What is printed?
  1. A. 2
  2. B. 4
  3. C. 6
  4. D. -1

Correct answer: B. 4

Both 2-move routes pass through 0001 or 0010, and 3 moves cannot work because one extra move cannot be undone. Turning another wheel away and back costs 2 extra: 0000 → 1000 → 1010 → 1011 → 0011 = 4 moves.

More Coding Interview Problems questions

Exams that ask this topic