EasyNo. 1652
Defuse the Bomb — LeetCode 1652 Python Solution
- Pattern
- Sliding Window
- Topics
- Array, Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k.
Example
- Input
- code = [5,7,1,4], k = 3
- Output
- [12,10,16,13]
- Explanation
- Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.
Python solution
class Solution:
def decrypt(self, code: List[int], k: int) -> List[int]:
n = len(code)
ans = [0] * n
if k == 0:
return ans
for i in range(n):
if k > 0:
for j in range(i + 1, i + k + 1):
ans[i] += code[j % n]
else:
for j in range(i + k, i):
ans[i] += code[(j + n) % n]
return ansComplexity
- Time
- O(n × |k|), ignoring the space consumption of the answer, the space complexity is O(1)
- Space · auxiliary
- O(1)
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 1652. Defuse the Bomb is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Sliding Window.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0239 | Sliding Window Maximum | Hard |
| 0643 | Maximum Average Subarray I | Easy |
| 1052 | Grumpy Bookstore Owner | Medium |
| 1343 | Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold | Medium |
| 1438 | Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit | Medium |
| 1499 | Max Value of Equation | Hard |
Frequently asked questions
- How hard is LeetCode 1652. Defuse the Bomb?
LeetCode 1652. Defuse the Bomb is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1652. Defuse the Bomb?
The Python solution on this page runs in O(n × |k|), ignoring the space consumption of the answer, the space complexity is O(1).
- What is the space complexity of LeetCode 1652. Defuse the Bomb?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1652. Defuse the Bomb cover?
LeetCode 1652. Defuse the Bomb is tagged Array and Sliding Window on LeetCode.