NeetCode #379LC-862HardStack
← Back to All Problems#379 · #862 · Shortest Subarray with Sum at Least K(和至少为 K 的最短子数组)
📌 Problem Statement & Constraints
Given an integer array
nums and an integer k, return the length of the shortest non-empty subarray with a sum of at least k. If no such subarray exists, return -1. Constraints: 1 <= nums.length <= 10^5, -10^5 <= nums[i] <= 10^5, 1 <= k <= 10^9.💡 Core Algorithmic Approaches
- Prefix sums are required, and because
numsmay contain negative values a plain sliding window does not apply. - Maintain a deque of indices with increasing prefix sums: it holds the candidates for the left end.
- For each right end
i, pop from the front whileprefix[i] - prefix[front] >= k, recording the length; those fronts are exhausted because a lateriwould give a longer subarray. - Then pop from the back any index whose prefix sum is at least
prefix[i], sinceidominates it as a left end.
💻 Benchmark Python3 Implementation
class Solution:
def shortestSubarray(self, nums: List[int], k: int) -> int:
from collections import deque
n = len(nums)
prefix = [0] * (n + 1)
for i, x in enumerate(nums):
prefix[i + 1] = prefix[i] + x
dq = deque() # indices with increasing prefix sums
best = float("inf")
for i in range(n + 1):
# shrink from the front while the sum is large enough
while dq and prefix[i] - prefix[dq[0]] >= k:
best = min(best, i - dq.popleft())
# i dominates any earlier index with a >= prefix sum
while dq and prefix[dq[-1]] >= prefix[i]:
dq.pop()
dq.append(i)
return best if best != float("inf") else -1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each index enters and leaves the deque at most once.
💾 Space Complexity
O(n) for the prefix array and the deque.
⚠️ Interview Pitfalls & Follow-ups
- Using a sliding window: it fails with negative values, since the sum is not monotone in the window bounds.
- Popping from the front without recording the length first: the length must be captured before the pop.
- Omitting the back-popping step: the deque would no longer be increasing in prefix sum and the front would not be the best candidate.
- Forgetting the
-1case: no subarray may reach the required sum.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Stack Problems
中文速览与面试要点
和至少为 K 的最短子数组
给你一个整数数组 nums 和一个整数 k,找出 nums 中和至少为 k 的 最短非空子数组 ,并返回该子数组的长度。如果不存在这样的子数组,返回 −1。子数组是数组中 连续 的一部分。约束:1 ≤ nums.length ≤ 10^5;-10^5 ≤ nums[i] ≤ 10^5;1 ≤ k ≤ 10^9。
核心要点
- 前缀和 + 单调双端队列(标准解) :先构造前缀和数组 prefix ( prefix[i] 表示前 i 个元素之和)。
- 问题转化 :找最小的 j − i 使 prefix[j] − prefix[i] >= k (i < j)。
- 为什么不能用普通滑动窗口 :nums 含 负数 ,前缀和不是单调的,窗口收缩条件不成立。
- 单调队列的作用 :维护一个 递增 的前缀和下标队列。遍历 j 时:① 若队首满足 prefix[j] − prefix[队首] >= k ,则记录答案并弹出队首(因为它不可能给出更短的长度);② 若 prefix[j] <= prefix[队尾] ,则弹出队尾(因为 j 更靠右且前缀和更小,更优)。
常见陷阱
- 用滑动窗口 :nums 含负数,前缀和不单调,滑动窗口会出错。必须用单调队列。
- 队列维护成递减而非递增 :应维护 递增 的前缀和(队首最小),这样才容易满足 prefix[j] − prefix[队首] >= k 。
- 步骤 ① 中忘记弹出队首 :会导致重复计算且无法保证 O(n)。弹出是安全的——队首对应的起点更靠左,若它能满足条件,后续更靠右的 j 只会给出更长的长度。
- 步骤 ② 用 < 而非 <= :用 <= 可以弹出相等的前缀和,让队列更紧凑;用 < 也能得到正确答案。
- 返回值判断写成 best == n + 1 :用 best <= n 判断更直观。
参考实现
from collections import deque
class Solution:
def shortestSubarray(self, nums: list[int], k: int) -> int:
n = len(nums)
# 前缀和:prefix[i] = nums[0..i-1] 之和
prefix = [0] * (n + 1)
for i, x in enumerate(nums):
prefix[i + 1] = prefix[i] + x
best = n + 1
dq = deque() # 存下标,前缀和单调递增
for j in range(n + 1):
# ① 检查队首是否满足条件
while dq and prefix[j] - prefix[dq[0]] >= k:
if j - dq[0] < best:
best = j - dq[0]
dq.popleft() # 队首已无利用价值(更长)
# ② 维护队列的单调性
while dq and prefix[j] <= prefix[dq[-1]]:
dq.pop()
dq.append(j)
return best if best <= n else -1