Video in progress

Strong Middle 🧠 Problem solving

How do you count the contiguous subarrays whose sum is exactly K? The array also contains negative numbers.

A prefix sum and a HashMap<prefix, count>: at each step I add to the answer how many times sum - K has been seen before. A sliding window doesn't work because of the negative numbers, and this approach is O(n).

📖 Answer

In an interview people often suggest a sliding window first. With negative numbers the window isn't monotonic: adding an element can decrease the sum, so you can't tell when to move the left edge.

The right idea: if prefix[j] - prefix[i] = K, then the range (i, j] is an answer. So for each j you need to know how many times prefix[j] - K has occurred before.

static int countSubarrays(int[] nums, int k) {
    Map<Long, Integer> seen = new HashMap<>();
    seen.put(0L, 1);          // the empty prefix — for subarrays that start at the beginning
    long sum = 0;
    int count = 0;
    for (int x : nums) {
        sum += x;
        count += seen.getOrDefault(sum - k, 0);
        seen.merge(sum, 1, Integer::sum);
    }
    return count;
}

People make mistakes in two places:

  • forgetting seen.put(0L, 1), so the answers that start at the beginning of the array are lost;
  • writing merge before getOrDefault, which makes an empty subarray get counted when K = 0.

Using long isn't for nothing: 10⁵ numbers of size 10⁵ exceed what an int can hold.

Memory is O(n). The same template carries over to "subarrays whose sum is divisible by k" (the key is sum % k, with the negative remainder corrected) and "the longest subarray with equal numbers of 0s and 1s".