Solve Open the Lock BFS
Company: Snapchat
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates the ability to model the lock as a state-space and apply graph traversal and shortest-path techniques (breadth-first search) to determine minimal move sequences under constraints.
Constraints
- 1 <= deadends.length <= 500
- Each deadends[i] and target has exactly 4 digits ('0'..'9').
- Each move turns one wheel by ±1 with wrap-around ('9'->'0', '0'->'9').
- If "0000" is itself a deadend, the lock can never move and the answer is -1.
- target may equal "0000" (answer 0).
Examples
Input: (["0201", "0101", "0102", "1212", "2002"], "0202")
Expected Output: 6
Explanation: A valid 6-move sequence is 0000 -> 1000 -> 1100 -> 1200 -> 1201 -> 1202 -> 0202. Note 0102 is a deadend, so the more direct route 0000 -> 0001 -> 0002 -> 0102 ... is blocked, forcing the longer 6-move path.
Input: (["8888"], "0009")
Expected Output: 1
Explanation: Turn the last wheel down once: 0 -> 9 wraps around, so 0000 -> 0009 in a single move. The deadend 8888 is never on the path.
Hints
- Model each 4-digit combination as a node in an unweighted graph; an edge connects two combinations that differ by a single ±1 wheel turn. Minimum moves on an unweighted graph = shortest path, which is exactly what BFS finds.
- From any state, generate its 8 neighbors by turning each of the 4 wheels up and down by one, using modulo 10 for wrap-around (so digit 9 goes to 0 and 0 goes to 9).
- Treat deadends as blocked nodes you may never enter (skip them when expanding), and use a visited set so you never revisit a combination. Handle the edge cases first: if "0000" is a deadend return -1, and if target == "0000" return 0.