Magicsheet logo

Open the Lock

Medium
48.5%
Updated 6/1/2025

Open the Lock

What is this problem about?

The Open the Lock problem presents a combination lock with 4 wheels (0000 to 9999). Each turn moves one wheel up or down by 1 (wrapping around). Given a target combination and a set of deadends (forbidden combinations), find the minimum turns to reach the target from 0000. This coding problem is a classic BFS shortest-path problem on a state graph.

Why is this asked in interviews?

J.P. Morgan, Uber, Goldman Sachs, Microsoft, Meta, Amazon, Google, and Bloomberg ask this because it tests BFS on an implicit graph of states. The state space (10^4 = 10000 combinations) is small enough for BFS, and deadend avoidance is the constraint. The array, BFS, hash table, and string interview pattern is the core.

Algorithmic pattern used

BFS on state graph. Start at "0000". For each state, generate up to 8 neighbors (each of 4 wheels can go up or down). Skip states in deadends or already visited. BFS guarantees minimum turns (unweighted shortest path). Return level when target is reached, -1 if not reachable.

Example explanation

target="0202", deadends=["0201","0101","0102","1212","2002"]. BFS from "0000". Level 1: ["1000","0100","0010","0001","9000","0900","0090","0009"]. Level 2: continue expanding. Minimum turns = 6 (some path avoids deadends to reach "0202").

Common mistakes candidates make

  • Not checking deadends before adding to queue (may enter deadend states).
  • Not checking if "0000" itself is a deadend (must return -1 immediately).
  • Not using a visited set (BFS can revisit states infinitely).
  • Off-by-one in wrap-around: (9+1)%10=0, (0-1+10)%10=9.

Interview preparation tip

Open the Lock exemplifies BFS on an implicit state graph. The state is the 4-digit combination. Generate neighbors by modifying one character at a time with wrap-around. This pattern applies to puzzle BFS problems: Rubik's cube states, word ladder, sliding tile puzzles. Always verify: (1) deadend check before processing, (2) "0000" deadend check, (3) modular arithmetic for wrap-around digits.

Similar Questions