Leetcode #1652: Defuse the Bomb
In this guide, we solve Leetcode #1652 Defuse the Bomb in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Array, Sliding Window
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
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 ans
Complexity
The time complexity is , ignoring the space consumption of the answer, the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.