#752

Open the Lock

Medium
ArrayHash TableStringBreadth-First SearchBreadth-First SearchGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a breadth-first search (BFS) strategy to explore the shortest path to the target. By treating each lock state as a node in a graph, we can efficiently find the minimum number of moves required.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a queue with the starting state '0000' and a set for visited states.
  2. 2Step 2: For each state, generate all possible next states by turning each wheel up or down.
  3. 3Step 3: Check if the next state is the target or a deadend.
  4. 4Step 4: If valid, add it to the queue and mark it as visited.
  5. 5Step 5: Continue until the target is found or all possibilities are exhausted.
solution.py25 lines
1# Full working Python code
2from collections import deque
3
4def openLock(deadends, target):
5    dead_set = set(deadends)
6    if '0000' in dead_set:
7        return -1
8    queue = deque(['0000'])
9    visited = set(['0000'])
10    turns = 0
11    while queue:
12        for _ in range(len(queue)):
13            current = queue.popleft()
14            if current == target:
15                return turns
16            for i in range(4):
17                for move in [-1, 1]:
18                    next_state = list(current)
19                    next_state[i] = str((int(current[i]) + move) % 10)
20                    next_state = ''.join(next_state)
21                    if next_state not in visited and next_state not in dead_set:
22                        visited.add(next_state)
23                        queue.append(next_state)
24        turns += 1
25    return -1

Complexity note: The time complexity is linear with respect to the number of states explored, which is limited to 10,000. The space complexity is also linear because we store visited states and the queue.

  • 1Each wheel can be treated as an independent dimension, leading to a combinatorial explosion of states.
  • 2Using BFS guarantees that the first time we reach the target, it is through the shortest path.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.