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.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Sliding Window Problems
#219 · #219Contains Duplicate II#220 · #121Best Time to Buy and Sell Stock#221 · #2379Minimum Recolors to Get K Consecutive Black Blocks#222 · #1984Minimum Difference Between Highest and Lowest of K Scores#223 · #1343Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold#224 · #1052Grumpy Bookstore Owner
中文速览与面试要点
拆炸弹
你有一个炸弹需要拆除,时间紧迫!你的情报员会给你一个长度为 n 的 循环 数组 code 以及一个密钥 k。为了得到正确的密码,你需要替换掉每一个数字。所有数字会 同时 被替换。如果 k > 0 ,将第 i 个数字用 接下来 k 个数字之和替换;如果 k < 0 ,将第 i 个数字用 之前 k 个数字之和替换;如果 k == 0 ,将第 i 个数字用 0 替换。由于 code 是循环的, code[n−1] 的下一个元素是 code[0] ,而 code[0] 的前一个元素是 code[n−1] 。返回解密后的数组。约束:n == code.length;1 ≤ n ≤ 100;1 ≤ code[i] ≤ 100;-(n − 1) ≤ k ≤ n − 1。
核心要点
- 定长窗口 + 循环取模(标准解) :目标窗口长度固定为 |k| 。用取模实现环形访问。
- k > 0 :第 i 个位置取 code[(i+1) % n] ... code[(i+k) % n] 之和。
- k < 0 :第 i 个位置取 code[(i-1) % n] ... code[(i-|k|) % n] 之和(Python 的负取模自动回绕到末尾)。
- k == 0 :全部为 0,直接返回。
- 优化 :也可以用「两倍数组 + 定长窗口滚动和」做到 O(n),但本题 n ≤ 100,直接求和已足够。
常见陷阱
- 忘记取模导致越界 : code[i + j] 在 i + j >= n 时会越界。必须用 % n 。
- k < 0 时用 code[i - j] 而不取模 :当 i − j < 0 时,Python 的负下标会静默索引到数组末尾,恰好等价于环形访问——虽然结果正确,但依赖这一行为不够清晰,显式写 % n 更好。
- k == 0 时未特判 :此时 range(1, 1) 为空,求和结果为 0,恰好正确;但显式返回 [0]*n 更清晰。
- 「同时替换」的含义 :必须基于 原数组 计算所有结果,不能边算边覆盖。本解用新数组 res 收集,天然正确。
参考实现
class Solution:
def decrypt(self, code: list[int], k: int) -> list[int]:
n = len(code)
if k == 0:
return [0] * n
res = []
if k > 0:
for i in range(n):
res.append(sum(code[(i + j) % n] for j in range(1, k + 1)))
else:
for i in range(n):
res.append(sum(code[(i - j) % n] for j in range(1, -k + 1)))
return res
# 滚动窗口版本(O(n)):
# n = len(code); kk = abs(k)
# if k == 0: return [0]*n
# arr = code + code
# cur = sum(arr[1:kk+1]) if k > 0 else sum(arr[n-kk:n])
# ... 逐位滚动