LeetCode #752 Medium

Open the Lock

Open the Lock is LeetCode 752 (Medium). A combination lock has 4 wheels, each showing a digit from 0 to 9. The lock starts at "0000".

  • One move turns one wheel by one slot, up or down.
  • The wheels wrap around: turning 9 up gives 0, and turning 0 down gives 9.
  • deadends is a list of codes that jam the lock. If the wheels ever show one of them, the lock stops turning, so a path may never pass through a deadend.

Given a target code, return the minimum number of moves to reach it from "0000", or -1 if it cannot be reached.

There are at most 500 deadends, and every code is exactly 4 digits, so the whole space is only 10⁴ codes.

Constraints
  • 1 <= deadends.length <= 500
  • deadends[i].length == 4
  • target.length == 4
  • target will not be in the list deadends.
  • target and deadends[i] consist of digits only.
bfsimplicit-graph
Open on LeetCode ↗
02

Intuition

Treat each 4-digit code as a node in a graph. Each code has exactly 8 neighbours: pick one of 4 wheels and turn it up or down. Every move costs the same, one turn, so the question "fewest moves from 0000 to target" is a shortest path in an unweighted graph. That is what breadth-first search answers.

BFS visits codes in rings: first 0000, then every code 1 turn away, then every code 2 turns away, and so on. The first time it reaches target, the ring number is the minimum, because every shorter distance has already been fully explored.

Deadends are simply nodes the search may never enter.

How to spot this pattern

"Minimum number of steps" between states, where every step costs the same and each state has a small fixed set of next states, is BFS on an implicit graph. You never build the graph; you generate neighbours on the fly. Open the Lock is the textbook case; Word Ladder (LeetCode 127), Minimum Genetic Mutation (433) and Sliding Puzzle (773) have the same shape.

03

Approach

Try it first

Before reading on, write the function that lists the 8 neighbours of a code, including the wrap from 0 to 9. Then decide where the deadends go so the search never steps on one.

1

Seed the visited set with the deadends

seen = set(deadends), so the search treats every deadend as already explored and never steps onto one, with no separate check in the loop. If "0000" is in it, the lock is jammed before the first move: return -1. Otherwise add "0000" and put it in the queue.

2

Expand level by level

Keep a counter turns. Each pass of the outer loop processes exactly the codes that were in the queue when it began, which is one full ring, then does turns += 1. Every code popped during a pass is exactly turns moves from the start.

3

Generate the 8 neighbours

For each wheel i and each move in (+1, -1), set digit i to (digit + move) % 10. In Python % already maps -1 to 9; in C++ and Java add 10 before taking % 10. Any neighbour not in seen is added to seen and to the queue.

4

Stop at the target

When the popped code equals target, return turns: the first hit is the fewest moves. If the queue empties without finding it, every reachable code has been visited and the target is not one of them: return -1.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def openLock(self, deadends: List[str], target: str) -> int:
▶3 seen = set(deadends)
▶4 if "0000" in seen:
▶5 return -1
▶6 seen.add("0000")
▶7 queue = deque(["0000"])
▶8 turns = 0
▶9 while queue:
▶10 for _ in range(len(queue)):
▶11 code = queue.popleft()
▶12 if code == target:
▶13 return turns
▶14 for i in range(4):
▶15 digit = int(code[i])
▶16 for move in (1, -1):
▶17 nxt = code[:i] + str((digit + move) % 10) + code[i + 1 :]
▶18 if nxt not in seen:
▶19 seen.add(nxt)
▶20 queue.append(nxt)
▶21 turns += 1
▶22 return -1
start0000target0008turns0deadends1000900001000900001000900001new: queuedseen alreadydeadendtargetqueue, ring 0emptyqueued for ring 10deadends start in seen
seen7 codesthe deadends
target0008
Every code is a node and one turn is an edge of length 1, so the fewest turns is a BFS shortest path. Putting the deadends into seen before starting means BFS treats them as already visited and never steps on one; no separate check is needed.
expanding0000target0008turns0neighbourswheel 0wheel 1wheel 2wheel 3updown10009000010009000010009000010009new: queuedseen alreadydeadendtargetqueue, ring 0emptyqueued for ring 11pop 0000: 1 new queued
code0000ring 0, not the target
new1queued
seen9 codes
Pop the start code. 1 new code goes to the back of the queue, 1 turn from the start; 7 are deadends (1000, 9000, 0100, 0900, 0010, 0090, 0001) and stay blocked. Note 0009: turning 0 down wraps to 9, so it is one turn away.
expandingtarget0008turns1new: queuedseen alreadydeadendtargetqueue, ring 10009queued for ring 20ring 0 done → turns = 1
turns1
ring 11 codenow being expanded
Every code in ring 0 has been expanded, so everything now in the queue is exactly 1 turn from 0000. Bump turns and start the next ring of 1.
expanding0009target0008turns1neighbourswheel 0wheel 1wheel 2wheel 3updown10099009010909090019009900000008new: queuedseen alreadydeadendtargetqueue, ring 1emptyqueued for ring 27pop 0009: 7 new queued
code0009ring 1, not the target
new7queued
seen16 codes
Pop 0009; it is not the target. 7 new codes go to the back of the queue, all 2 turns from the start; 1 was already queued or visited, so it is skipped: it already has a distance no larger than this one. The target 0008 is among them, but this code checks the target on pop, so it is answered when its turn in the queue comes.
expandingtarget0008turns2new: queuedseen alreadydeadendtargetqueue, ring 2100990090109090900190099+1 morequeued for ring 30ring 1 done → turns = 2
turns2
ring 27 codesnow being expanded
Every code in ring 1 has been expanded, so everything now in the queue is exactly 2 turns from 0000. Bump turns and start the next ring of 7.
expanding1009target0008turns2neighbourswheel 0wheel 1wheel 2wheel 3updown20090009110919091019109910001008new: queuedseen alreadydeadendtargetqueue, ring 2900901090909001900990008queued for ring 36pop 1009: 6 new queued
code1009ring 2, not the target
new6queued
seen22 codes
Pop 1009; it is not the target. 6 new codes go to the back of the queue, all 3 turns from the start; 1 was already queued or visited, so it is skipped: it already has a distance no larger than this one; 1 is a deadend (1000) and stays blocked.
expanding9009target0008turns2neighbourswheel 0wheel 1wheel 2wheel 3updown00098009910999099019909990009008new: queuedseen alreadydeadendtargetqueue, ring 201090909001900990008queued for ring 312pop 9009: 6 new queued
code9009ring 2, not the target
new6queued
seen28 codes
Pop 9009; it is not the target. 6 new codes go to the back of the queue, all 3 turns from the start; 1 was already queued or visited, so it is skipped: it already has a distance no larger than this one; 1 is a deadend (9000) and stays blocked.
expanding0109target0008turns2neighbourswheel 0wheel 1wheel 2wheel 3updown11099109020900090119019901000108new: queuedseen alreadydeadendtargetqueue, ring 20909001900990008queued for ring 316pop 0109: 4 new queued
code0109ring 2, not the target
new4queued
seen32 codes
Pop 0109; it is not the target. 4 new codes go to the back of the queue, all 3 turns from the start; 3 were already queued or visited, so they are skipped: they already have a distance no larger than this one; 1 is a deadend (0100) and stays blocked.
expanding0909target0008turns2neighbourswheel 0wheel 1wheel 2wheel 3updown19099909000908090919099909000908new: queuedseen alreadydeadendtargetqueue, ring 2001900990008queued for ring 320pop 0909: 4 new queued
code0909ring 2, not the target
new4queued
seen36 codes
Pop 0909; it is not the target. 4 new codes go to the back of the queue, all 3 turns from the start; 3 were already queued or visited, so they are skipped: they already have a distance no larger than this one; 1 is a deadend (0900) and stays blocked.
expanding0019target0008turns2neighbourswheel 0wheel 1wheel 2wheel 3updown10199019011909190029000900100018new: queuedseen alreadydeadendtargetqueue, ring 200990008queued for ring 322pop 0019: 2 new queued
code0019ring 2, not the target
new2queued
seen38 codes
Pop 0019; it is not the target. 2 new codes go to the back of the queue, all 3 turns from the start; 5 were already queued or visited, so they are skipped: they already have a distance no larger than this one; 1 is a deadend (0010) and stays blocked.
expanding0099target0008turns2neighbourswheel 0wheel 1wheel 2wheel 3updown10999099019909990009008900900098new: queuedseen alreadydeadendtargetqueue, ring 20008queued for ring 324pop 0099: 2 new queued
code0099ring 2, not the target
new2queued
seen40 codes
Pop 0099; it is not the target. 2 new codes go to the back of the queue, all 3 turns from the start; 5 were already queued or visited, so they are skipped: they already have a distance no larger than this one; 1 is a deadend (0090) and stays blocked.
expanding0008target0008turns2new: queuedseen alreadydeadendtargetqueue, ring 2emptyqueued for ring 3240008 is the target → return 2
code0008equals target
turns2
Found 0008 in ring 2. BFS finished every ring before this one without meeting the target, so no path with fewer turns exists. That is why the first hit is the answer, and the search stops here.
05

Common pitfalls

Forgetting the wrap-around in C++ or Java

✗ Wrong
nxt[i] = '0' + (code[i] - '0' + move) % 10;
✓ Right
nxt[i] = '0' + (code[i] - '0' + move + 10) % 10;

In C++ and Java -1 % 10 is -1, not 9, so turning 0 down produces the character before '0' instead of '9'. Adding 10 first keeps the value non-negative. Python's % already returns 9.

Marking a code seen when it is popped, not when it is queued

✗ Wrong
code = queue.popleft()
seen.add(code)
✓ Right
if nxt not in seen:
    seen.add(nxt)
    queue.append(nxt)

Many codes share neighbours, so the same code gets queued many times before it is first popped. The answer stays correct, but the queue can grow several times larger and the run can time out.

Not checking whether 0000 is a deadend

✗ Wrong
seen = set(deadends)
queue = deque(["0000"])
✓ Right
if "0000" in seen:
    return -1

If the starting code is jammed, no move is possible at all and the answer is -1, even when target is "0000". Without the check the search happily expands from a jammed lock.

Counting turns per pop instead of per level

✗ Wrong
code = queue.popleft()
turns += 1
✓ Right
for _ in range(len(queue)):
    ...
turns += 1

turns must count rings, not codes. Either process one full level per pass, or store the distance with each code in the queue as (code, d).

06

Edge cases

Target is 0000

The first pop is "0000", which equals the target, so the answer is 0.

Target is walled in

If all 8 neighbours of the target are deadends (LeetCode's third example, target "8888"), nothing can reach it. BFS learns that only after visiting every other reachable code, up to 10⁴ of them, which is still fast, and returns -1.

07

Complexity

Time
O(Aᴺ · N² + D)
Space
O(Aᴺ + D)
A = 10 digits per wheel and N = 4 wheels, so there are Aᴺ = 10⁴ codes. The BFS visits each code once; each has 2N = 8 neighbours, and building one is O(N) string work, so O(Aᴺ · N²) in total. D is the number of deadends, loaded into a set once. The visited set and the queue hold at most Aᴺ codes.
08

Open the Lock FAQ

Why BFS and not DFS?

Every move costs the same, and BFS explores codes in order of distance, so the first time it reaches the target is guaranteed to be the fewest moves. DFS would find a path, often a very long one, and would have to search everything to be sure no shorter one exists.

How does bidirectional BFS speed up the solution?

Search from "0000" and from target at the same time, always expanding the smaller frontier, and stop when the two meet. Each side only needs to go about half the distance, and because the number of codes grows quickly with distance, that visits far fewer codes. It is the usual follow-up when an interviewer asks for something faster than plain BFS.

What does the Python solution use for the queue?

collections.deque, because popleft() is O(1). Popping from the front of a plain list is O(n) and makes the whole search much slower.