SDE & MLE Prep

752. Open the Lock

Problem

A lock has 4 wheels with digits 0–9; one move turns one wheel by one step, wrapping 9 ↔ 0. It starts at "0000", and reaching any combination in deadends jams it. Return the minimum moves to reach target, or −1 if impossible.

Example: deadends = ["0201","0101","0102","1212","2002"], target = "0202" → 6

States are 4-digit strings; each move turns one wheel ±1 → 8 neighbours. BFS from "0000", skipping deadends.

Complexity: O(10⁴ · 8).

class Solution:
    def openLock(self, deadends: List[str], target: str) -> int:
        dead = set(deadends)
        if "0000" in dead:
            return -1
        q, seen, steps = deque(["0000"]), {"0000"}, 0
        while q:
            for _ in range(len(q)):
                cur = q.popleft()
                if cur == target:
                    return steps
                for i in range(4):
                    d = int(cur[i])
                    for nd in ((d + 1) % 10, (d - 1) % 10):
                        nxt = cur[:i] + str(nd) + cur[i + 1:]
                        if nxt not in seen and nxt not in dead:
                            seen.add(nxt)
                            q.append(nxt)
            steps += 1
        return -1