Open the Lock

Medium

Topics
ArrayStringHash TableBFS

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

start0000
target0202
turns each wheel needs0202
deadends02010101010212122002
the target digitsa position the lock jams on
Reaching 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.
One turn moves a single wheel one step; the wheels cannot be moved together.
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

start0000
target0009
turns each wheel needs0001
deadends8888
the target digitsa position the lock jams on
Those distances add to 1, which the answer matches — no deadend sits on the direct route here.
Input:  words = ["8888"], target = "0009"
Output: 1
Explanation: Turn the last wheel down from 0 to 9, which wraps in one step.

Example 3

start0000
target8888
turns each wheel needs2222
deadends0000
the target digitsa position the lock jams on
Reaching 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

  1. Put every deadend into a visited set. If "0000" is among them, return -1.
  2. If the target is "0000", return 0.
  3. Explore outward from "0000" at distance 0, ring by ring.
  4. For a position, generate its eight neighbours by turning each of the four wheels up and down, wrapping with % 10.
  5. Skip any neighbour already visited, which covers both deadends and positions seen at an equal or smaller distance.
  6. 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 0 to 9 is 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 -1
SensAI
Beta
Tap the mic to stop voice mode