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?- A. 2
- B. 4
- C. 6
- 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
- Problem: Water level t floods every cell of height ≤ t. Find the smallest t at which you can swim from the top-left to the bottom-right…
- Problem: Connect all points with minimum total Manhattan-distance wiring (dense-graph Prim in O(n²)). python def mst(p): n = len(p); dist…
- Problem: Courses with prerequisites (u → v means u before v); any number of courses can be taken per semester. Find the minimum number of…
- Problem: Answer lowest-common-ancestor queries with binary lifting (up[j][v] = 2^j-th ancestor). python par = [-1, 0, 0, 1, 1, 2, 3, 3, 4…
- A COMPLETE binary tree has n nodes. Counting them by comparing the leftmost and rightmost depths at each node and recursing into only one…
- Problem: Rebuild a BST from its preorder traversal (using value bounds) and print its postorder. python def postfrompre(pre): i, out = 0…