Open the Lock solution explained

Open the Lock is a shortest-path problem on an unweighted graph: each four-digit code is a node, and each single turn of one wheel up or down is an edge, so every code has eight neighbours. Run a BFS from 0000 that never enters a blocked code, and the first time it reaches the target, the BFS level is the fewest turns. There are only 10,000 codes, so the search is O(10⁴ · 8) at worst; a two-ended BFS from both the start and the target usually explores far fewer.

By Published 7 min read

Restating the problem

A lock has four wheels, each showing a digit from 0 to 9, and starts at 0000. One move turns one wheel by one step, up or down, and the wheels wrap: turning 9 up gives 0 and turning 0 down gives 9. You are given a list of blocked codes; if the lock ever shows one of them, it jams for good. Return the fewest moves to reach the target code, or -1 if it cannot be reached.

Cases made up for this page
Blocked codesTargetAnswerWhy
none09092Turn the second and fourth wheels down once each.
0101, 1010, 0110, 100111114One turn per wheel still works, for example via 1000, 1100, 1110.
0101, 1010, 0110, 1001, 1011, 0111, 1101, 111011116Every code with three 1s and a 0 is blocked, so the last move has to come from a code such as 2111 or 1121, a detour of two extra turns.
all eight neighbours of 0000any other code-1No first move is possible.
0000any-1The lock is jammed from the start.
none00000Already there.
Cases made up for this page. Scroll sideways on a small screen.

What it tests

The prompt sounds like a puzzle, and some candidates try to reason digit by digit. The interviewer is waiting for you to say that this is a graph you build on the fly: states are codes, moves are edges, every move costs the same, so breadth-first search gives the shortest path. After that the details matter: generating the eight neighbours with wrap-around, checking the start against the blocked list, and marking codes as seen when they enter the queue.

A note on brute force

Without blocked codes there is a direct answer: for each wheel, take the shorter way round, min(d, 10 - d), and add them up. Blocked codes break that formula, because the shortest route may need a detour, as the third example shows. Trying every sequence of moves up to some length grows like 8 to the power of that length, so a search that never revisits a code is the real baseline.

BFS from 0000

Put the blocked codes in a set for O(1) lookups. If 0000 is in it, return -1. Otherwise start a queue at 0000 with distance 0. Pop a code, and if it is the target, return its distance. Else generate its eight neighbours and push every one that is not blocked and not yet seen, with distance one more. Because BFS explores codes in order of distance, the first time the target comes out of the queue, its distance is the minimum.

from collections import deque


def neighbours(code):
    for i in range(4):
        d = int(code[i])
        for step in (1, -1):
            yield code[:i] + str((d + step) % 10) + code[i + 1:]


def open_lock(deadends, target):
    blocked = set(deadends)
    if "0000" in blocked:
        return -1
    dist = {"0000": 0}
    queue = deque(["0000"])
    while queue:
        code = queue.popleft()
        if code == target:
            return dist[code]
        for nxt in neighbours(code):
            if nxt not in blocked and nxt not in dist:
                dist[nxt] = dist[code] + 1
                queue.append(nxt)
    return -1
BFS over codes as strings. At most 10,000 codes, 8 neighbours each.

Using Python's % 10 handles both directions of the wrap, since (0 - 1) % 10 is 9 in Python. That is not true in every language, which is why the C++ version below adds 9 instead of subtracting 1.

#include <queue>
#include <string>
#include <vector>
using namespace std;

int openLock(const vector<string>& deadends, const string& target) {
    vector<int> dist(10000, -1);
    vector<bool> blocked(10000, false);
    for (const string& d : deadends) blocked[stoi(d)] = true;
    if (blocked[0]) return -1;
    const int goal = stoi(target);
    const int place[4] = {1000, 100, 10, 1};
    queue<int> q;
    q.push(0);
    dist[0] = 0;
    while (!q.empty()) {
        int code = q.front();
        q.pop();
        if (code == goal) return dist[code];
        for (int p : place) {
            int digit = code / p % 10;
            for (int step : {1, 9}) {           // +9 mod 10 is the same as -1
                int next = code + ((digit + step) % 10 - digit) * p;
                if (!blocked[next] && dist[next] == -1) {
                    dist[next] = dist[code] + 1;
                    q.push(next);
                }
            }
        }
    }
    return -1;
}
C++17 BFS on integers 0 to 9999, with arrays instead of hash sets.

Encoding codes as integers removes string building and hashing. The digit at a place value p is code / p % 10, and changing it means adding the difference times p. A distance array of 10,000 entries doubles as the seen set.

Two-ended BFS

When start and target are both known, you can search from both at once. Keep one frontier around 0000 and one around the target, and each round expand whichever frontier is smaller by one level. As soon as a newly generated code belongs to the other frontier, the two searches have met, and the number of rounds so far is the answer. The idea is that two searches of half the depth usually touch far fewer codes than one search of the full depth.

def open_lock_two_ends(deadends, target):
    blocked = set(deadends)
    if "0000" in blocked or target in blocked:
        return -1
    if target == "0000":
        return 0
    front, back = {"0000"}, {target}
    seen = {"0000", target}
    turns = 0
    while front and back:
        if len(front) > len(back):        # always grow the smaller side
            front, back = back, front
        turns += 1
        grown = set()
        for code in front:
            for i in range(4):
                d = int(code[i])
                for step in (1, -1):
                    nxt = code[:i] + str((d + step) % 10) + code[i + 1:]
                    if nxt in back:
                        return turns      # the two searches meet
                    if nxt not in blocked and nxt not in seen:
                        seen.add(nxt)
                        grown.add(nxt)
        front = grown
    return -1
Grow the smaller side each round; stop when the sides touch.

This version needs one extra check that the plain BFS gets for free: a blocked target must return -1 up front, because the backward search would otherwise start from it. The turns counter can be shared by both sides, because every round adds exactly one move to the path that will eventually connect them.

Complexity

With w wheels of 10 digits there are N = 10ʷ codes; here w = 4
ApproachTimeExtra space
BFSO(N · w) to visit codes and their 2w neighbours, plus O(b) to load b blocked codesO(N + b)
Two-ended BFSSame worst case, usually much less in practiceO(N + b)
With string codesMultiply by w for building and hashing each stringSame
With w wheels of 10 digits there are N = 10ʷ codes; here w = 4. Scroll sideways on a small screen.

Edge cases

  • The start 0000 is blocked: -1 without searching.
  • The target is 0000: 0 moves.
  • The target itself is blocked: -1.
  • All eight neighbours of the start blocked: -1.
  • Codes that need the wrap, such as reaching 9000 in one move.
  • Duplicate entries in the blocked list, which a set absorbs.

Mistakes

  • Keeping blocked codes in a list and searching it every time, which makes each check linear.
  • Marking codes as seen when popped instead of when pushed, so the queue fills with duplicates.
  • Forgetting the wrap from 0 down to 9 in languages where -1 % 10 is negative.
  • Using DFS, which finds a path but not the shortest one.
  • Not checking whether the start code is blocked.

How to explain it out loud

Fictional example

Seeing the lock as a graph
Candidate
Each code is a state, and each move turns one wheel one step, so every code has eight neighbours. All moves cost the same, so the fewest moves is a BFS distance.
Candidate
I'll keep blocked codes in a set, return minus one if 0000 is blocked, and mark each code as seen when I push it.
Interviewer
How big can the search get?
Candidate
There are ten thousand codes, each with eight neighbours, so at most eighty thousand edge checks. If it needed to be faster, I'd search from both ends and stop when the frontiers meet.

Implicit-graph BFS also solves Snakes and Ladders, where board squares are the states and die rolls are the moves, and Shortest Path in Binary Matrix on an explicit grid. For reachability without distances, see Keys and Rooms, and for a grid search where the cost is the highest cell rather than the step count, Swim in Rising Water.

Going through it with Natively

Questions like this reward naming the state space quickly. Natively can read the lock problem from a screenshot on Mac or Windows and show an approach and code in its overlay, so you can check your neighbour generation and wrap-around. When you rehearse the explanation aloud, its transcript shows whether you said why BFS gives the minimum. Find out more on the AI interview assistant page.

Questions people ask

How do you solve Open the Lock?

Run a BFS from 0000 where each code's neighbours are the eight codes one wheel turn away, skipping blocked codes. The BFS level at which the target appears is the fewest turns.

Why is BFS the right choice for Open the Lock?

Every turn costs the same, so BFS visits codes in order of distance and the first time it reaches the target is a shortest route. DFS would not guarantee that.

What if 0000 is a blocked code?

Return -1 immediately. The lock jams at the start, so no move is possible.

What is bidirectional BFS in Open the Lock?

Search from 0000 and from the target at the same time, always growing the smaller frontier, and stop when they meet. It usually explores far fewer codes than a one-sided search.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP