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 nums, which may contain negative numbers, and an integer k. A subarray is a run of one or more neighbouring numbers from the array. Return the length of the shortest subarray whose sum is at least k, or -1 if no subarray reaches k.

Example 1
Input: nums = [1], k = 1
Output: 1
Example 2
Input: nums = [1, 2], k = 4
Output: -1
Explanation: even the whole array only adds up to 3.
Example 3
Input: nums = [2, -1, 2], k = 3
Output: 3
Explanation: only the whole array reaches 3.
Example 4
Input: nums = [84, -37, 32, 40, 95], k = 167
Output: 3
Explanation: 32 + 40 + 95 = 167.
Solution

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] and k = 3, no single number reaches 3. The two pairs of neighbours, 2 + (-1) and -1 + 2, both give 1. Only all three numbers together reach 3, so the answer is 3.

Example 4 shows why the negative numbers make this hard. The whole array [84, -37, 32, 40, 95] adds up to 214, which is enough. Can we drop numbers from the left to make it shorter? Dropping 84 leaves 130, too little, so it seems we must stop. Yet dropping -37 as well brings the sum back up to 167, and 32, 40 and 95 are the answer. So looking at one number at a time from the left can give up too early.

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 i numbers prefix[i]. Look at the picture below.

Bars for the running totals of 84, -37, 32, 40, 95: prefix[0] to prefix[5] are 0, 84, 47, 79, 119 and 214. The arrow from prefix[2] up to prefix[5] shows 214 - 47 = 167, the sum of 32, 40 and 95, length 3. prefix[1] = 84 is dropped because prefix[2] is later and lower.

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], 47, up to prefix[5], 214. The gap, 167, is exactly 32 + 40 + 95, the three numbers between those two bars.

So the question becomes: for each bar, which earlier bar is at least k lower and as close as possible? The run starts after that earlier bar, and its length is the distance between the two bars.

Now look at the dashed bar marked "dropped:", prefix[1] = 84. prefix[2] comes after it and is lower. Any later bar that is at least k above 84 is also at least k above 47, and closer to it. So 84 can never give the shortest run, and we can forget it. Forgetting every bar like that leaves bars that only rise from left to right, and that is the key to a fast solution.

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 i and ends at position j - 1 has the sum prefix[j] - prefix[i], and its length is j - i. With an array of n numbers, prefix has n + 1 entries, because prefix[0] is 0.

The simple way is to try every pair of a start i and an end j. That is about n²/2 pairs: 5 billion for 100,000 numbers, far too slow. We want to look at each end once and find its start without trying them all.

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, then the left marker drops numbers while the sum stays large enough. Minimum Size Subarray Sum works this way.

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 ArrayDeque is such a list; its name is short for "double-ended queue", usually just called a deque. Before a new position j joins at the back, positions at the back whose total is at least prefix[j] are removed. A deque kept in rising order this way is called a monotonic deque.

When an earlier total is done

Because the totals in the deque rise, the front holds the lowest one, the easiest to beat by k. If prefix[j] minus the front's total is at least k, we have a run of length j minus the front position. Any later end would give a longer run from that same start, so the front is removed for good, and the next front is checked the same way.

In Example 4, the deque holds positions 0, 2, 3 and 4 when prefix[5] = 214 arrives. The gap 214 - 0 is 214, a run of length 5, so position 0 goes. Then 214 - 47 is 167, a run of length 3, so position 2 goes. Finally 214 - 79 is 135, too small, so the checks stop.

Keeping the totals in long

Can a running total get too big? A Java int holds values up to 2,147,483,647, about 2.1 billion. Three numbers of one billion already add up to three billion. Past its largest value, an int wraps around to the most negative values, which is called overflow. A long holds far bigger values, so the totals are kept in a long[].

Java Solution

The method shortestSubarray works in these steps:

  1. First, build the running totals in long[] prefix, with n + 1 entries: prefix[0] is 0, and each next entry adds one number of nums.
  2. Set best, the shortest length found so far, to Integer.MAX_VALUE, and create an empty ArrayDeque called dq for the positions of the earlier totals.
  3. Visit every position j from 0 to n with a loop. Inside it, a first while loop checks the front: as long as prefix[j] minus the front's total is at least k, it updates best with the length j minus the front position and removes the front.
  4. A second while loop removes positions from the back whose total is at least prefix[j]. Then j joins at the back.
  5. After the loop, return best, or -1 if it never changed.

The main method runs the four examples, a second input with negative numbers, an array where every number is negative, and three numbers of one billion whose total does not fit in an int.

Java
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:

Output
1
-1
3
3
3
-1
3

Look at the fourth line: 3 for [84, -37, 32, 40, 95], where the plain sliding window from the positive-only problem gives 5. The fifth line, 3 for [-28, 81, -20, 28, -29] with k = 89, is the run 81, -20, 28. The sliding window returns -1 here. It only drops a number from the left once the sum is large enough, and with the -28 still in, the sum never gets past 61.

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[] for the totals, the last total overflows to a negative number, and the same method returns -1.

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 while loops together take at most n + 1 removals.
  • Space: O(n). The prefix array has n + 1 long values, and the deque can hold up to n + 1 positions when the totals keep rising.

A monotonic deque also drives Sliding Window Maximum, where it keeps the largest number of a moving window at the front.