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 numskk[1, 2][1, 2, 3]
Example 1
Output: 2
Explanation: [1, 1] at positions 0 and 1, and [1, 1] at positions 1 and 2.
Example 2
Output: 2
Explanation: [1, 2] and [3].
Example 3
Output: 3
Explanation: [1] at position 0, [1, -1, 1], and [1] at position 2.
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]k = 3
Each number sits between two running totals. The stretch [1, 2][3]
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][1, -1, 1][1]
That is the key insight: at each position, the number of stretches ending there with sum kk
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 kHashMapHashMap
The total before the first number
What about stretches that start at the first number, such as [1, 2]
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
Java Solution
The method subarraySum
- First, create the map
withseen , 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.new HashMap<>() - Set
, the running total, andtotal , the number of stretches found, to 0.count - Loop over the numbers with
, and add each one tofor (int x : nums) .total - Inside the loop, look up
withtotal - k , which gives 0 for a total never seen, and add the result toseen.getOrDefault(total - k, 0) .count - Then record the current total with
. It adds 1 to the total's count, or stores 1 if the total is new.seen.merge(total, 1, Integer::sum) - After the loop, return
.count
The maink = 0[0, 0][1, 2][3, 4, -7, 3]
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:
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][0][0][0, 0]
The fifth line, 0 for [1, 2]mergeseen.put(0, 1)[1, 2]
The last line comes from [3, 4, -7, 3][3, 4, -7][4, -7, 3]
The original implementation,
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
and onegetOrDefault , and each takes O(1) time on average in amerge .HashMap - Space: O(n). The map
holds at most one entry per different running total, and there are n + 1 running totals, counting the 0 before the first number.seen
The same idea, with the remainder after dividing by k