NeetCode #237LC-1652EasySliding Window
← Back to All Problems#237 · #1652 · Defuse the Bomb(拆炸弹)
📌 Problem Statement & Constraints
You have a bomb with a circular code array
nums and a key k. If k > 0, replace each element with the sum of the next k elements; if k < 0, with the sum of the previous |k| elements; if k == 0, replace every element with 0. Return the resulting array. Constraints: 1 <= nums.length <= 100, 1 <= nums[i] <= 100, -(n-1) <= k <= n-1.💡 Core Algorithmic Approaches
- The array is circular, so indices are taken modulo
n. - For
k > 0, sum thekelements after indexi; fork < 0, sum the|k|elements before it. - A direct implementation is O(n * |k|), which is acceptable given
n <= 100. - For large inputs a sliding window would make it O(n), but the straightforward version is clearer here.
💻 Benchmark Python3 Implementation
class Solution:
def decrypt(self, code: List[int], k: int) -> List[int]:
n = len(code)
if k == 0:
return [0] * n
res = []
for i in range(n):
if k > 0:
s = sum(code[(i + j) % n] for j in range(1, k + 1))
else:
s = sum(code[(i - j) % n] for j in range(1, -k + 1))
res.append(s)
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n * |k|): with n <= 100 this is at most 10^4 operations. A sliding window would reduce it to O(n).
💾 Space Complexity
O(n) for the result.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting the modulo when indexing: the array is circular, so
(i + j) % nis required. - Using
range(k)instead ofrange(1, k+1): the window excludes the element itself. - Handling
k == 0inside the loop: returning an all-zero array upfront is simpler. - Assuming
kis positive: it can be negative, in which case the sum looks backwards.