Subarray Sum Equals K

Count the runs of neighbouring numbers in an array that add up to k, with running totals and a map.

You are given an array of integers nums and an integer k. Count the subarrays whose numbers add up to k. A subarray is a run of one or more numbers that sit next to each other in the array, such as [1, 2] in [1, 2, 3]. The numbers in the array can be negative.

Example 1
Input: nums = [1, 1, 1], k = 2
Output: 2
Explanation: [1, 1] at positions 0 and 1, and [1, 1] at positions 1 and 2.
Example 2
Input: nums = [1, 2, 3], k = 3
Output: 2
Explanation: [1, 2] and [3].
Example 3
Input: nums = [1, -1, 1], k = 1
Output: 3
Explanation: [1] at position 0, [1, -1, 1], and [1] at position 2.
Solution

The Idea

Think of a bank statement. Money comes in and goes out day by day, and the statement shows the balance after each day. To find out how much came in between Monday and Thursday, you do not add up every entry. You take Thursday's balance and subtract the balance from before Monday.

The same subtraction works on any stretch of neighbouring numbers in an array, that is, on any subarray. Take Example 2, [1, 2, 3] with k = 3, and keep a running total, like the balance. It is 0 before the first number, then 1, 3 and 6. Look at the picture below.

The numbers 1, 2, 3 with the running totals 0, 1, 3 and 6 between them. The stretch [1, 2] sums to 3 - 0 = 3, and the stretch [3] sums to 6 - 3 = 3.

Each number sits between two running totals. The stretch [1, 2], in teal, starts after the total 0 and ends at the total 3, so its sum is 3 - 0 = 3. The stretch [3], in orange, starts after 3 and ends at 6, so its sum is 6 - 3 = 3. Those are the two answers of Example 2.

So the sum of a stretch is the running total at its end minus the running total just before its start. That turns the question around. Standing on the total 6, which stretches ending there add up to 3? Exactly those that start after an earlier total of 6 - 3 = 3. There is one such total, so one stretch ends there.

An earlier total can also appear more than once. In Example 3, [1, -1, 1], the running totals are 0, 1, 0 and 1. On the last total, 1, a stretch with sum 1 must start after an earlier total of 0. The total 0 appears twice, before the first number and after -1, so two stretches end there: [1, -1, 1] and the last [1].

That is the key insight: at each position, the number of stretches ending there with sum k is how many earlier running totals equal the current total minus k. A running total like this is usually called a prefix sum, because it is the sum of the beginning, or prefix, of the array.

Solution Approach

Turning that idea into code means settling four things: why not try every stretch, how to count earlier totals quickly, where the first total comes from, and whether to look up or record a total first.

Trying every stretch

Why not simply add up every stretch? Pick each start, then move the end one number at a time and keep a sum. That works, but an array of n numbers has about n²/2 stretches, so 10,000 numbers already mean about 50 million sums.

A sliding window does not help either. It moves two markers along the array and keeps the stretch between them, growing it while the sum is too small and shrinking it while the sum is too big. That only works when a longer stretch always has a bigger sum. With negative numbers it does not: adding -1 makes the sum smaller.

Counting earlier totals

How do we find out quickly how many earlier totals equal the current total minus k? Keep a HashMap from each running total seen so far to how many times it was seen. A lookup in a HashMap takes about the same time however many entries it holds. So each position costs one lookup and one update, and one pass over the array is enough.

The total before the first number

What about stretches that start at the first number, such as [1, 2]? Their sum is the current total minus 0, the total before anything was added. Nothing has put that 0 in the map yet, so the map starts with 0, seen once.

Looking up before recording

Should the current total go into the map before or after the lookup? After. A stretch holds at least one number, so it must start after an earlier total, never at the current one. Looking up first keeps the current total out of its own search. The order only matters when k is 0, because then the total being looked up is the current total itself.

Java Solution

The method subarraySum works in these steps:

  1. First, create the map seen with new HashMap<>(), from running total to how many times it was seen. Put 0 in it with a count of 1, for the total before the first number.
  2. Set total, the running total, and count, the number of stretches found, to 0.
  3. Loop over the numbers with for (int x : nums), and add each one to total.
  4. Inside the loop, look up total - k with seen.getOrDefault(total - k, 0), which gives 0 for a total never seen, and add the result to count.
  5. Then record the current total with seen.merge(total, 1, Integer::sum). It adds 1 to the total's count, or stores 1 if the total is new.
  6. After the loop, return count.

The main method runs the three examples, then three arrays with k = 0: [0, 0], [1, 2], which has no stretch with sum 0, and [3, 4, -7, 3], where a negative number brings the running total back down.

Java
import java.util.HashMap;
import java.util.Map;

public class SubarraySumEqualsK {

    public static int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> seen = new HashMap<>();   // running total -> how many times seen
        seen.put(0, 1);                                 // the total before the first number
        int total = 0;
        int count = 0;
        for (int x : nums) {
            total += x;
            count += seen.getOrDefault(total - k, 0);   // earlier totals that leave exactly k
            seen.merge(total, 1, Integer::sum);         // record this total for later positions
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(subarraySum(new int[] {1, 1, 1}, 2));
        System.out.println(subarraySum(new int[] {1, 2, 3}, 3));
        System.out.println(subarraySum(new int[] {1, -1, 1}, 1));
        System.out.println(subarraySum(new int[] {0, 0}, 0));
        System.out.println(subarraySum(new int[] {1, 2}, 0));
        System.out.println(subarraySum(new int[] {3, 4, -7, 3}, 0));
    }
}

Running it prints:

Output
2
2
3
3
0
2

The answers 2, 2 and 3 at the top match the three examples. Look at the fourth line: [0, 0] gives 3, because the first [0], the second [0] and [0, 0] all add up to 0. The running total stays 0, so the first lookup finds one earlier 0 and the second finds two. That is why the map keeps counts and not just which totals were seen.

The fifth line, 0 for [1, 2], depends on looking up before recording. With the merge line moved above the lookup, the same input returns 2: each total finds itself, as if an empty stretch added up to 0. Leaving out seen.put(0, 1) breaks something else: Example 2 then returns 1, because [1, 2] starts at the first number.

The last line comes from [3, 4, -7, 3], whose running totals are 0, 3, 7, 0 and 3. The total 0 comes back after -7, which gives [3, 4, -7], and the total 3 comes back at the end, which gives [4, -7, 3].

The original implementation, SubarraysSumEqualToK.java, is on GitHub.

Complexity

The loop visits each number once and does a fixed amount of map work for it.

  • Time: O(n), because the loop visits each of the n numbers once, compared with O(n²) for trying every stretch. Each number costs one getOrDefault and one merge, and each takes O(1) time on average in a HashMap.
  • Space: O(n). The map seen holds at most one entry per different running total, and there are n + 1 running totals, counting the 0 before the first number.

The same idea, with the remainder after dividing by k in place of the running total, solves Continuous Subarray Sum.