Fewest Dial Turns to Open a Four-Wheel Lock Avoiding Deadends

Last updated: November 29, 2026

Quick Overview

A lock has four wheels with digits 0 to 9 that wrap around, starting at '0000'. Each move turns one wheel by one step; some codes are deadends that freeze the lock. Return the fewest moves to reach a target code, or -1.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


A lock has four wheels with digits 0 to 9 that wrap around, starting at '0000'. Each move turns one wheel by one step; some codes are deadends that freeze the lock. Return the fewest moves to reach a target code, or -1.

A Google technical screen classic for state-space BFS. The graph is never given; the interviewer wants you to define states and neighbors, recognize BFS gives shortest paths in unweighted graphs, and handle the tricky start-is-deadend case.

What the Interviewer Expects
  • Model each 4-digit code as a node with 8 neighbors
  • Use BFS for shortest path on an unweighted graph
  • Treat deadends as pre-visited nodes
  • Handle start in deadends and start equal to target
  • Mention bidirectional BFS as an optimization
Key Topics to Cover
state-space search
BFS
shortest path
bidirectional BFS
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Implement bidirectional BFS and explain the speedup.
  • What if each wheel has a different number of digits?
  • What if turning wheel i costs a different amount?
  • Return the actual sequence of codes.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Start '0000', target string, list of deadends.
  • Each move changes one wheel by +1 or -1 mod 10.
  • Cannot pass through a deadend.
  • Return minimum moves or -1....
High-Level Design

The state space has 10410^4 codes, each with 8 neighbors, small enough for plain BFS. I put the deadends into the visited set before starting so they are never expanded. If '0000' is itself a deadend...


Submit Your Answer
Markdown supported