Logo for ammarahmed.ca
Medium
Jan 13, 2026
#graph
#bfs

752. Open the Lock

You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

The lock initially starts at '0000', a string representing the state of the 4 wheels.

You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.

Example 1:

1Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202" 2Output: 6 3Explanation: 4A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202". 5Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid, 6because the wheels of the lock become stuck after the display becomes the dead end "0102".

Example 2:

1Input: deadends = ["8888"], target = "0009" 2Output: 1 3Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".

Example 3:

1Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" 2Output: -1 3Explanation: We cannot reach the target without getting stuck.
  • 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.

            Constraints:

            Notes

            Intuition

            Model this as a graph problem where each lock combination is a node and each wheel turn is an edge. Each state has exactly 8 neighbors (4 wheels × 2 directions). BFS finds the shortest path from "0000" to the target.

            Implementation

            Create a function to generate all 8 neighbors of a combination (turn each wheel up or down using mod 10). Start BFS from "0000" with a queue storing (combo, turns) pairs. Track visited states to avoid cycles. For each state, check neighbors—skip if visited or a deadend. If a neighbor equals the target, return turns + 1.

            Edge-cases

            Check if "0000" is a deadend (return -1 immediately). Also handle the case where the target is "0000" (return 0).

            • Time: O(10⁴) — at most 10,000 possible states
              • Space: O(10⁴) — visited set and queue

                Complexity

                Solution

                1from typing import List 2from collections import deque 3 4class Solution: 5 def combo2int(self, combo: str) -> List[int]: 6 return [int(c) for c in combo] 7 8 def int2combo(self, arr: List[int]) -> str: 9 return "".join([str(n) for n in arr]) 10 11 def neighbours(self, combo: str) -> List[str]: 12 result = [] 13 for i in range(len(combo)): 14 up_n = self.combo2int(combo) 15 down_n = self.combo2int(combo) 16 up_n[i] = (up_n[i] + 1) % 10 17 down_n[i] = (down_n[i] - 1) % 10 18 result.append(self.int2combo(up_n)) 19 result.append(self.int2combo(down_n)) 20 return result 21 def openLock(self, deadends: List[str], target: str) -> int: 22 dead = set(deadends) 23 start = "0000" 24 25 if start in dead: 26 return -1 27 if start == target: 28 return 0 29 q = deque([(start, 0)]) 30 visited = { start } 31 32 while q: 33 curr, turns = q.popleft() 34 for n in self.neighbours(curr): 35 if n in dead or n in visited: 36 continue 37 if n == target: 38 return turns + 1 39 q.append((n, turns + 1)) 40 visited.add(n) 41 return -1 42 43 44 45if __name__ == "__main__": 46 # Include one-off tests here or debugging logic that can be run by running this file 47 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 48 solution = Solution() 49