Shortest Subarray with Sum at Least K
Problem Description
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, return -1.
Note: nums may contain negative numbers — sliding window alone won't work.
Example 1:
Input: nums = [1], k = 1
Output: 1
Example 2:
Input: nums = [1,2], k = 4
Output: -1
Example 3:
Input: nums = [2,-1,2], k = 3
Output: 3
DE Shaw Tier 1 — maps to LC 862.
Optimal: Prefix sums + monotonic deque O(n). Build prefix sum array P. For each r, pop from front of deque while P[r] - P[deque.front] >= k (valid window, try to shrink). Push r to back after popping any indices with P value >= P[r] (they can never be better left endpoints).
Example Test Cases
Example 1
Input: [[1],1]
Expected: 1
Example 2
Input: [[1,2],4]
Expected: -1
Example 3
Input: [[2,-1,2],3]
Expected: 3
Example 4
Input: [[84,-37,32,40,95],167]
Expected: 3
Run your code to see the results