Unlock Four Wheels with the Fewest Turns

Quick Overview

Unlock Four Wheels with the Fewest Turns. A four-wheel lock starts at "0000". One move turns one decimal digit forward or backward by one, wrapping between 0 and 9.

Unlock Four Wheels with the Fewest Turns

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem A four-wheel lock starts at "0000". One move turns one decimal digit forward or backward by one, wrapping between 0 and 9. Any deadends code jams the lock and cannot be traversed. Return the minimum moves to target, or -1 if unreachable. ```cpp class Solution { public: int openLock(vector<string>& deadends, string target); }; ``` ### Examples **Example 1:** ```text deadends = ["5555"], target = "0011" Output: 2 Explanation: Turn the last two wheels once each; two changed digits require at least two moves. ``` **Example 2:** ```text deadends = ["0000"], target = "0001" Output: -1 Explanation: The initial state is already jammed. ``` ### Constraints - There are 1 through 500 deadend strings. - Every code and target contains exactly four decimal digits. - The target is absent from deadends. ### Contract considerations Preserve wraparound and forbid traversing jammed states. ```hint Read the boundary condition What are the eight neighbors of one lock code? ``` ### Boundary reminders Preserve wraparound and forbid traversing jammed states.

Overview: Unlock Four Wheels with the Fewest Turns. A four-wheel lock starts at "0000". One move turns one decimal digit forward or backward by one, wrapping between 0 and 9.

Amazon logo
Amazon
Source window: 0–3 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

A four-wheel lock starts at "0000". One move turns one decimal digit forward or backward by one, wrapping between 0 and 9. Any deadends code jams the lock and cannot be traversed. Return the minimum moves to target, or -1 if unreachable.

class Solution {
public:
    int openLock(vector<string>& deadends, string target);
};

Examples

Example 1:

deadends = ["5555"], target = "0011"
Output: 2
Explanation: Turn the last two wheels once each; two changed digits require at least two moves.

Example 2:

deadends = ["0000"], target = "0001"
Output: -1
Explanation: The initial state is already jammed.

Constraints

  • There are 1 through 500 deadend strings.
  • Every code and target contains exactly four decimal digits.
  • The target is absent from deadends.

Contract considerations

Preserve wraparound and forbid traversing jammed states.

Boundary reminders

Preserve wraparound and forbid traversing jammed states.