Minimum Length Subarray with Sum At Least N
viaLeetCode
Problem Find the minimum length of a contiguous subarray whose sum is >= n; return 0 if none exists.
Input / Output
- Input: int array nums, int n. Output: min length or 0.
Constraints
- Array up to 10^5; with positive integers O(n) is expected; ask whether negatives can appear — it changes the algorithm entirely.
Example
- nums = [2,3,1,2,4,3], n = 7 → 2 ([4,3]).
Expected approach
- Positives: sliding window — extend right accumulating; while sum >= n, record length and shrink left. Monotone sums make the window valid. O(n)/O(1).
- With negatives: window monotonicity breaks. Prefix sums + monotonic deque: for each r find the latest l with prefix[r] − prefix[l] >= n, keeping the deque of prefix indices increasing by value (Shortest Subarray with Sum at Least K). O(n). Explaining WHY the simple window fails on negatives is the senior probe. Binary search over prefix sums works only when prefixes are monotone (all positives).
asked …