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?- A. 4 3 -1
- B. 4 3 15
- C. 4 17 -1
- 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
- Problem: Shortest paths from node 1 in a weighted DAG (negative edges allowed): topologically sort with Kahn's algorithm, then relax edges…
- Problem: An investor starts with capital w and may finish at most k projects; project i needs capital[i] to start and adds profits[i] when…
- Problem: A single CPU receives tasks (enqueue time, duration). When idle it starts the available task with the shortest duration (ties…
- Problem: Walk along buildings of given heights; climbing up by d needs d bricks or one ladder (going down is free). Return the furthest…
- Problem: Find the smallest range [lo, hi] that contains at least one number from each of k sorted lists (min-heap of one pointer per list…
- Problem: Choose the root(s) that minimise the height of an unrooted tree. Repeatedly strip all current leaves; the last 1 or 2 nodes are…