Open the Lock — LeetCode 752 Python Solution
MediumBreadth-First SearchArrayHash TableString
- Problem
- #752
- Pattern
- Breadth-First Search
- Reading time
- 6 min
- Source
- leetcode.com
The problem
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'.
Example
- Input
- deadends = ["0201","0101","0102","1212","2002"], target = "0202"
- Output
- 6
- Explanation
- A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
Python solution
Python
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
def next(s):
res = []
s = list(s)
for i in range(4):
c = s[i]
s[i] = '9' if c == '0' else str(int(c) - 1)
res.append(''.join(s))
s[i] = '0' if c == '9' else str(int(c) + 1)
res.append(''.join(s))
s[i] = c
return res
if target == '0000':
return 0
s = set(deadends)
if '0000' in s:
return -1
q = deque([('0000')])
s.add('0000')
ans = 0
while q:
ans += 1
for _ in range(len(q)):
p = q.popleft()
for t in next(p):
if t == target:
return ans
if t not in s:
q.append(t)
s.add(t)
return -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Breadth-First Search
Expand outward level by level, so the first time you arrive is the shortest way. LeetCode 752. Open the Lock is filed here because LeetCode tags it Breadth-First Search, which is the vocabulary this hub collects.
The breadth-first search guide has the Python template for the pattern and the 233 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 752. Open the Lock?
- LeetCode 752. Open the Lock is rated Medium on LeetCode.
- What is the time complexity of LeetCode 752. Open the Lock?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 752. Open the Lock?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 752. Open the Lock cover?
- LeetCode 752. Open the Lock is tagged Breadth-First Search, Array, Hash Table and String on LeetCode.