Defuse the Bomb — LeetCode 1652 Python Solution
EasyArraySliding Window
- Problem
- #1652
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n \times |k|), ignoring the space consumption of the answer, the space complexity is O(1) |
| Space | O(1) auxiliary |
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
LeetCode 239Sliding Window MaximumHardLeetCode 643Maximum Average Subarray IEasyLeetCode 1052Grumpy Bookstore OwnerMediumLeetCode 1343Number of Sub-arrays of Size K and Average Greater than or Equal to ThresholdMediumLeetCode 1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitMediumLeetCode 1499Max Value of EquationHard
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 \times |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.