Shortest Subarray with Sum at Least K
Find the shortest run of neighbouring numbers whose sum reaches k, when the array can hold negative numbers.
You are given an array of integers numskkk
Example 1
Output: 1
Example 2
Output: -1
Explanation: even the whole array only adds up to 3.
Example 3
Output: 3
Explanation: only the whole array reaches 3.
Example 4
Output: 3
Explanation: 32 + 40 + 95 = 167.
The Idea
Think of the array as a bank account over a few days: each number is what came in or went out that day. The question is the fewest days in a row that together brought in at least k
Example 3 is small enough to check by hand. With [2, -1, 2]k = 3
Example 4 shows why the negative numbers make this hard. The whole array [84, -37, 32, 40, 95]
What helps is writing down a running total: the sum of the first numbers, one more at a time. For Example 4 the totals are 0 (no numbers yet), 84, 47, 79, 119 and 214. A running total like this is called a prefix sum, and we call the one after the first iprefix[i]
Each bar is one running total, and the green numbers in the "nums:" row under the bars are the numbers of the array that move the total up or down between two bars. The sum of any run of numbers is the gap between two bars. The arrow goes from prefix[2]prefix[5]
So the question becomes: for each bar, which earlier bar is at least k
Now look at the dashed bar marked "dropped:", prefix[1]prefix[2]kk
Solution Approach
Turning that idea into code means settling five things: how to get the sum of any run, why the usual window trick does not work here, which earlier totals to keep, when an earlier total is no longer needed, and which type holds the totals.
Sums of runs from prefix sums
How do we get the sum of a run quickly? Counting positions from 0, the run that starts at position ij - 1prefix[j] - prefix[i]j - iprefixprefix[0]
The simple way is to try every pair of a start ij
Why the usual window does not work
When all numbers are positive, a sliding window solves this: two markers mark a run, the right marker adds numbers until the sum reaches k
It relies on one rule: dropping a number from the left always makes the sum smaller. A negative number breaks the rule, as Example 4 showed. The window reaches 214 over all five numbers, drops 84, sees 130 and stops shrinking, so it reports 5 instead of 3.
Which earlier totals to keep
Which starts are worth remembering? The picture already answered that: when a new total is lower than or equal to an earlier one, the earlier one is never a better start, so we drop it. The totals that stay rise from left to right.
To hold them we need a list we can change at both ends. Java's ArrayDequejprefix[j]
When an earlier total is done
Because the totals in the deque rise, the front holds the lowest one, the easiest to beat by kprefix[j]kj
In Example 4, the deque holds positions 0, 2, 3 and 4 when prefix[5]
Keeping the totals in long
Can a running total get too big? A Java intintlonglong[]
Java Solution
The method shortestSubarray
- First, build the running totals in
, with n + 1 entries:long[] prefix is 0, and each next entry adds one number ofprefix[0] .nums - Set
, the shortest length found so far, tobest , and create an emptyInteger.MAX_VALUE calledArrayDeque for the positions of the earlier totals.dq - Visit every position
from 0 to n with a loop. Inside it, a firstj loop checks the front: as long aswhile minus the front's total is at leastprefix[j] , it updatesk with the lengthbest minus the front position and removes the front.j - A second
loop removes positions from the back whose total is at leastwhile . Thenprefix[j] joins at the back.j - After the loop, return
, or -1 if it never changed.best
The mainint
import java.util.ArrayDeque;
import java.util.Deque;
public class ShortestSubarrayWithSumAtLeastK {
public static int shortestSubarray(int[] nums, int k) {
int n = nums.length;
long[] prefix = new long[n + 1]; // prefix[i] = nums[0] + ... + nums[i-1]
for (int i = 0; i < n; i++) {
prefix[i + 1] = prefix[i] + nums[i];
}
int best = Integer.MAX_VALUE;
Deque<Integer> dq = new ArrayDeque<>(); // start indices, prefix values increasing
for (int j = 0; j <= n; j++) {
while (!dq.isEmpty() && prefix[j] - prefix[dq.peekFirst()] >= k) {
best = Math.min(best, j - dq.pollFirst()); // shortest for this start found
}
while (!dq.isEmpty() && prefix[dq.peekLast()] >= prefix[j]) {
dq.pollLast(); // a later, smaller prefix is always a better start
}
dq.offerLast(j);
}
return best == Integer.MAX_VALUE ? -1 : best;
}
public static void main(String[] args) {
System.out.println(shortestSubarray(new int[] {1}, 1));
System.out.println(shortestSubarray(new int[] {1, 2}, 4));
System.out.println(shortestSubarray(new int[] {2, -1, 2}, 3));
System.out.println(shortestSubarray(new int[] {84, -37, 32, 40, 95}, 167));
System.out.println(shortestSubarray(new int[] {-28, 81, -20, 28, -29}, 89));
System.out.println(shortestSubarray(new int[] {-5, -3}, 1));
int big = 1000000000;
System.out.println(shortestSubarray(new int[] {big, big, big}, 2000000001));
}
}
Running it prints:
1
-1
3
3
3
-1
3
Look at the fourth line: 3 for [84, -37, 32, 40, 95][-28, 81, -20, 28, -29]k = 89
The sixth line is -1: with only -5 and -3, every running total falls, so no total is ever 1 above an earlier one. The last line is the overflow check. The three numbers add up to 3,000,000,000, so all three together reach 2,000,000,001 and the answer is 3. With an int[]
Complexity
The work is one pass to build the running totals and one pass over them with the deque.
- Time: O(n), for an array of n numbers, because each of the n + 1 positions joins the deque once and leaves it at most once, from the front or the back, so all the
loops together take at most n + 1 removals.while - Space: O(n). The
array has n + 1prefix values, and the deque can hold up to n + 1 positions when the totals keep rising.long
A monotonic deque also drives