Shortest Subarray with Sum at Least K

Given an integer array `nums` (values may be negative) and an integer `k`, return the length of the shortest non-empty contiguous subarray whose sum is at least `k`. If no such subarray exists, return `-1`.

30:00

Shortest Subarray with Sum at Least K
hard
Free written solution
Topics
Companies

Given an integer array nums (values may be negative) and an integer k, return the length of the shortest non-empty contiguous subarray whose sum is at least k. If no such subarray exists, return -1.

Example 1:
Input: {"nums":[1],"k":1}
Output: 1
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • −105≤nums[i]≤105-10^5 \leq \text{nums}[i] \leq 10^5

  • 1≤k≤1091 \leq k \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1],"k":1}

prefix[0] = 0 stands for the empty prefix, so any subarray nums[i..j-1] sums to prefix[j] - prefix[i].

nums, k = 1

1

prefix sums (index 0..1), deque in blue

0

labels: prefix value at each index; gold = j, red = popped from back

deque: front to back (0)

empty

best length

none

Variables
VariableValue
k1
prefix[0]0
DepthFunction Call
Stack empty
0/8