Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: A 3-wheel lock starts at "000"; each move turns one wheel by ±1 (9 wraps to 0). Some codes are dead (the lock jams). Find the fewest moves to reach the target (BFS on 1000 states).

Problem: A 3-wheel lock starts at "000"; each move turns one wheel by ±1 (9 wraps to 0). Some codes are dead (the lock jams). Find the fewest moves to reach the target (BFS on 1000 states).
from collections import deque
def open_lock(dead, target):
    dead = set(dead)
    if "000" in dead: return -1
    q, seen = deque([("000", 0)]), {"000"}
    while q:
        s, d = q.popleft()
        if s == target: return d
        for i in range(3):
            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(["100", "900", "010", "090"], "110"), open_lock([], "919"), open_lock(["001", "009", "010", "090", "100", "900"], "555"))
What is printed?
  1. A. 4 3 -1
  2. B. 4 3 15
  3. C. 4 17 -1
  4. D. 2 3 -1

Correct answer: A. 4 3 -1

Without dead ends "110" takes 2 moves, but both first steps (100, 010) are dead, so a detour is needed: 000 → 001 → 101 → 111 → 110 = 4. "919": each 9 is one backward turn → 3 (not 9 + 1 + 9). Third: every neighbour of 000 is dead → −1 even though 555 itself is fine. O(10³ · 6).

More Coding Interview Problems questions

Exams that ask this topic