Open the Lock
Medium
Topics
A lock has four wheels, each showing a digit 0 to 9. One turn moves a single wheel one step, and the digits wrap, so 9 turns to 0 and 0 turns to 9.
The lock starts at "0000". words lists deadends: if the wheels ever show one of these, the lock jams and nothing further can be done. Return the fewest turns needed to reach target, or -1 if it cannot be reached.
LeetCode names the arguments deadends and target. The harness here calls the list words; it is the deadends.
Example 1
0202 from 0000 takes 6 turns. Each wheel wraps, so 0 to 9 is one turn down rather than nine up, and the bottom row is the shortest distance each wheel has to cover on its own. Those distances add to 4, below the answer, because the direct route passes through a deadend and has to detour around it.Input: words = ["0201","0101","0102","1212","2002"], target = "0202" Output: 6 Explanation: One route is 0000 to 1000 to 1100 to 1200 to 1201 to 1202 to 0202. Turning the last wheel first would pass through 0001 and then 0002 and 0102, which is blocked.
Example 2
Input: words = ["8888"], target = "0009" Output: 1 Explanation: Turn the last wheel down from 0 to 9, which wraps in one step.
Example 3
8888 from 0000 takes no number of turns, so the answer is -1. The starting position is itself a deadend, so the lock is jammed before anything is turned.Input: words = ["0000"], target = "8888" Output: -1 Explanation: The starting position is itself a deadend, so the lock is jammed before any turn.
Constraints
- 1 <= words.length <= 500
- words[i].length == 4
- target.length == 4
- All strings consist of digits
- target is not in words
Editorial — intuition, approach, complexity and pitfalls
Intuition
Every turn costs the same, one, so the cheapest route is found by exploring outward in rings of equal cost: first everything one turn away, then everything two turns away, and so on. The first time the target appears, it appears at its minimum.
A position is a four-digit string, and each position has exactly eight neighbours — four wheels, each turnable up or down. The wrap is the part people get wrong: going up from 9 gives 0, and down from 0 gives 9. Writing it as (digit + 1) % 10 and (digit + 9) % 10 makes both cases fall out without a branch.
Deadends are not obstacles to route around so much as positions that simply do not exist. The cleanest way to handle them is to seed the visited set with every deadend before starting, so the exploration can never step onto one and no check is needed in the loop.
That seeding also disposes of the nastiest case for free: if "0000" is itself a deadend, it is already visited and the exploration never begins, giving -1 without a special test.
Approach
- Put every deadend into a visited set. If
"0000"is among them, return-1. - If the target is
"0000", return0. - Explore outward from
"0000"at distance 0, ring by ring. - For a position, generate its eight neighbours by turning each of the four wheels up and down, wrapping with
% 10. - Skip any neighbour already visited, which covers both deadends and positions seen at an equal or smaller distance.
- Return the distance the moment the target is generated. If the exploration empties, return
-1.
Walkthrough
words = ["8888"], target = "0009"
ring 0: 0000
ring 1: turn each of the four wheels up and down
wheel 0: 1000 9000
wheel 1: 0100 0900
wheel 2: 0010 0090
wheel 3: 0001 0009 <-- target, at distance 1
answer 1
note 0009 comes from turning the last wheel DOWN from 0,
which wraps to 9. A solution that only turns wheels up
would need nine turns and report the wrong answer.
words = ["0000"], target = "8888"
the visited set starts as {"0000"}
the exploration cannot even begin from 0000
answer -1
why rings and not a cost-ordered queue
every turn costs exactly 1, so a plain ring-by-ring walk
already visits positions in order of distance.Complexity
- Time — O(10^4 * 4): there are ten thousand positions and each is expanded once into eight neighbours.
- Space — O(10^4): the visited set and the frontier, both bounded by the number of positions.
Common Pitfalls
- Forgetting that the digits wrap, so
0to9is one turn and not nine. - Not checking whether
"0000"is a deadend, which makes the answer 0 or a crash instead of-1. - Missing the case where the target is
"0000", whose answer is 0 turns. - Checking for a deadend when dequeuing instead of seeding the visited set, which works but needs the check in two places.
- Exploring depth first. Every turn costs the same, so only a ring-by-ring walk gives the minimum.
Full Solution — all languages
class Solution:
def openLock(self, words, target):
from collections import deque
# Seeding the visited set with the deadends means the walk can never
# step onto one, and the "0000 is a deadend" case needs no test.
seen = set(words)
if "0000" in seen:
return -1
if target == "0000":
return 0
seen.add("0000")
queue = deque([("0000", 0)])
while queue:
state, turns = queue.popleft()
for i in range(4):
digit = int(state[i])
# +1 and -1 with wraparound, neither needing a branch.
for moved in ((digit + 1) % 10, (digit + 9) % 10):
nxt = state[:i] + str(moved) + state[i + 1:]
if nxt == target:
return turns + 1
if nxt not in seen:
seen.add(nxt)
queue.append((nxt, turns + 1))
return -1import java.util.*;
class Solution {
public int openLock(String[] words, String target) {
Set<String> seen = new HashSet<>(Arrays.asList(words));
if (seen.contains("0000")) return -1;
if (target.equals("0000")) return 0;
seen.add("0000");
Deque<Object[]> queue = new ArrayDeque<>();
queue.add(new Object[]{"0000", 0});
while (!queue.isEmpty()) {
Object[] cur = queue.poll();
String state = (String) cur[0];
int turns = (Integer) cur[1];
for (int i = 0; i < 4; i++) {
int digit = state.charAt(i) - '0';
int[] moves = {(digit + 1) % 10, (digit + 9) % 10};
for (int m : moves) {
char[] chars = state.toCharArray();
chars[i] = (char) ('0' + m);
String nxt = new String(chars);
if (nxt.equals(target)) return turns + 1;
if (!seen.contains(nxt)) {
seen.add(nxt);
queue.add(new Object[]{nxt, turns + 1});
}
}
}
}
return -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int openLock(vector<string>& words, string target) {
unordered_set<string> seen(words.begin(), words.end());
if (seen.count("0000")) return -1;
if (target == "0000") return 0;
seen.insert("0000");
queue<pair<string, int>> q;
q.push({"0000", 0});
while (!q.empty()) {
auto cur = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int digit = cur.first[i] - '0';
int moves[2] = {(digit + 1) % 10, (digit + 9) % 10};
for (int m = 0; m < 2; m++) {
string nxt = cur.first;
nxt[i] = char('0' + moves[m]);
if (nxt == target) return cur.second + 1;
if (!seen.count(nxt)) {
seen.insert(nxt);
q.push({nxt, cur.second + 1});
}
}
}
}
return -1;
}
};/**
* @param {string[]} words
* @param {string} target
* @return {number}
*/ var openLock = function(words, target) {
const seen = new Set(words);
if (seen.has("0000")) return -1;
if (target === "0000") return 0;
seen.add("0000");
const queue = [["0000", 0]];
let head = 0;
while (head < queue.length) {
const [state, turns] = queue[head++];
for (let i = 0; i < 4; i++) {
const digit = state.charCodeAt(i) - 48;
for (const moved of [(digit + 1) % 10, (digit + 9) % 10]) {
const nxt = state.slice(0, i) + String(moved) + state.slice(i + 1);
if (nxt === target) return turns + 1;
if (!seen.has(nxt)) {
seen.add(nxt);
queue.push([nxt, turns + 1]);
}
}
}
}
return -1;
};