Skip to lesson

Subarray sum equals k

In Module 5.6 we saw that negative numbers break variable-size sliding windows for subarray sums. Combining Prefix Sums with a HashMap of prefix frequencies solves Subarray Sum Equals K in O(n) time for any integers—positive, zero, or negative.

Prefix sums plus a map of counts

Prefix sums plus a map of counts count the subarrays with sum k in one pass.

Java
int[] nums = {1, 2, 3};int k = 3;Map<Long, Integer> prefixCounts = new HashMap<>();prefixCounts.put(0L, 1);                               // the empty prefixlong currSum = 0;int count = 0;for (int x : nums) {    currSum += x;    count += prefixCounts.getOrDefault(currSum - k, 0); // earlier P[left] == currSum - k    prefixCounts.put(currSum, prefixCounts.getOrDefault(currSum, 0) + 1);}// count = 2: [1, 2] and [3]

The sum of the contiguous subarray nums[left .. right] is the difference between two prefix sums: sum(left .. right) = P[right + 1] - P[left] We want this subarray sum to equal k: P[right + 1] - P[left] = k ⇔ P[left] = P[right + 1] - k Look closely at that rearranged equation! When we are at index right with current running prefix sum currSum = P[right + 1], the number of valid subarrays ending at right with sum k is simply how many earlier prefix sums P[left] (0 ≤ left ≤ right) were equal to currSum - k!

Just like Two Sum, we maintain a Map<Long, Integer> prefixCounts that maps each prefix sum seen so far to how many times it has occurred.

  1. Create Map<Long, Integer> prefixCounts = new HashMap<>() and put (0L, 1).
  2. Initialize long currSum = 0 and int count = 0.
  3. For each x in nums: currSum += x.
  4. Add prefixCounts.getOrDefault(currSum - k, 0) to count.
  5. Increment prefixCounts.put(currSum, prefixCounts.getOrDefault(currSum, 0) + 1).

Counting subarrays with sum 2 in [1, 1, 1]

Step 1 of 4

Array: 1, 1, 1.
curr
0
count
0
seen sums
  1. 0
The map starts with the empty prefix sum 0. A subarray ends at the current index, so we look for an earlier prefix sum equal to curr - k.

Why the map starts with 0 and why it works with negative numbers

The map starts with the sum 0 seen once, so subarrays that begin at index 0 are counted too.

Example 1 · Brute force: running sum from every start (O(n²) time, O(1) space)

SubarraySumBrute.javaJava
public class SubarraySumBrute {    public static int subarraySum(int[] nums, int k) {        int total = 0;        for (int start = 0; start < nums.length; start++) {            long sum = 0;            for (int end = start; end < nums.length; end++) {                sum += nums[end];                if (sum == k) {                    total++;                }            }        }        return total;    }
    public static void main(String[] args) {        int[] a = {1, 1, 1};        System.out.println("[1, 1, 1], k=2 -> " + subarraySum(a, 2));        int[] b = {1, -1, 0};        System.out.println("[1, -1, 0], k=0 -> " + subarraySum(b, 0));        int[] c = {3, 4, 7, 2, -3, 1, 4, 2};        System.out.println("[3,4,7,2,-3,1,4,2], k=7 -> " + subarraySum(c, 7));    }}
Output
[1, 1, 1], k=2 -> 2
[1, -1, 0], k=0 -> 3
[3,4,7,2,-3,1,4,2], k=7 -> 4

What this code does

  • Every start and end pair is tried, and a running sum avoids a third loop. Negative numbers and zeroes are handled because nothing is skipped.
  • A two-pointer window cannot do this job, since negative numbers let the sum go up and down. A prefix sum with a map of earlier sums can.

Example 2 · Optimal: prefix sums plus a map of counts (O(n) time, O(n) space)

SubarraySumEqualsKDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class SubarraySumEqualsKDemo {    public static int subarraySum(int[] nums, int k) {        Map<Long, Integer> prefixCounts = new HashMap<>();        prefixCounts.put(0L, 1);        long currSum = 0;        int total = 0;
        for (int x : nums) {            currSum += x;            total += prefixCounts.getOrDefault(currSum - k, 0);            prefixCounts.put(currSum, prefixCounts.getOrDefault(currSum, 0) + 1);        }        return total;    }
    public static void main(String[] args) {        int[] a = {1, 1, 1};        System.out.println("[1, 1, 1], k=2 -> " + subarraySum(a, 2));        int[] b = {1, -1, 0};        System.out.println("[1, -1, 0], k=0 -> " + subarraySum(b, 0));        int[] c = {3, 4, 7, 2, -3, 1, 4, 2};        System.out.println("[3,4,7,2,-3,1,4,2], k=7 -> " + subarraySum(c, 7));    }}
Output
[1, 1, 1], k=2 -> 2
[1, -1, 0], k=0 -> 3
[3,4,7,2,-3,1,4,2], k=7 -> 4

What this code does

  • In [1, -1, 0] with k=0, the 3 valid subarrays are [1, -1], [1, -1, 0], and [0].
  • Because prefixCounts starts with {0L: 1}, when currSum returns to 0 at index 1 and index 2, it counts all earlier 0-prefixes.
  • Why it is faster: instead of trying every start, one lookup asks how many earlier prefix sums equal currSum - k. Every one of them is a start that makes a valid subarray.

Why do we seed prefixCounts.put(0L, 1) before the loop starts? Because before reading any elements (at index 0 of the padded prefix array), the empty prefix P[0] has sum 0 and has occurred once!

If a subarray starting at the very beginning nums[0 .. right] has currSum == k, then we look up currSum - k = 0 in the map. Seeding 0 -> 1 counts that prefix subarray [0 .. right] automatically without an if (currSum == k) branch. Why does this work with negative numbers? Because negative numbers can cause the same prefix sum to occur multiple times at different indices, and prefixCounts records all of them! For example, in nums = [1, -1, 1, -1] with k = 0, the prefix sums (starting from P[0] = 0) are 0, 1, 0, 1, 0. Every time 0 or 1 repeats, all previous occurrences of currSum - 0 are added in O(1) time.

Always look up prefixCounts.getOrDefault(currSum - k, 0) BEFORE incrementing the count of currSum in the map—otherwise, when k == 0, currSum would match with itself (an empty subarray of length 0)!

Subarrays divisible by k

Counting subarrays whose sum is a multiple of k (k > 0) uses the remainders of the prefix sums.

Example 3 · Subarray Sums Divisible by K normalizing negative remainders

SubarraysDivByKDemo.javaJava
public class SubarraysDivByKDemo {    public static int subarraysDivByK(int[] nums, int k) {        int[] remCounts = new int[k];        remCounts[0] = 1;        int currSum = 0;        int count = 0;
        for (int x : nums) {            currSum += x;            int rem = ((currSum % k) + k) % k;            count += remCounts[rem];            remCounts[rem]++;        }        return count;    }
    public static void main(String[] args) {        int[] nums = {4, 5, 0, -2, -3, 1};        System.out.println("Divisible by 5: " + subarraysDivByK(nums, 5));        int[] neg = {-1, 2, 9};        System.out.println("[-1, 2, 9] divisible by 2: " + subarraysDivByK(neg, 2));    }}
Output
Divisible by 5: 7
[-1, 2, 9] divisible by 2: 2

What this code does

  • In [-1, 2, 9] with k=2, the prefix sums are 0, -1, 1, 10. Normalized mod 2, they are 0, 1, 1, 0.
  • Without ((currSum % k) + k) % k, -1 % 2 would be -1 (crashing remCounts[-1] or failing to match +1)!

Example 4 · Contiguous Array (Equal 0s and 1s) & Continuous Subarray Sum (Length >= 2)

ContiguousArrayAndMultipleOfKDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class ContiguousArrayAndMultipleOfKDemo {    public static int findMaxLengthEqual01(int[] nums) {        Map<Integer, Integer> firstIdx = new HashMap<>();        firstIdx.put(0, -1);        int balance = 0, maxLen = 0;        for (int i = 0; i < nums.length; i++) {            balance += (nums[i] == 1) ? 1 : -1;            if (firstIdx.containsKey(balance)) {                maxLen = Math.max(maxLen, i - firstIdx.get(balance));            } else {                firstIdx.put(balance, i);            }        }        return maxLen;    }
    public static boolean checkSubarraySumMultipleOfK(int[] nums, int k) {        Map<Integer, Integer> firstIdx = new HashMap<>();        firstIdx.put(0, -1);        int sum = 0;        for (int i = 0; i < nums.length; i++) {            sum += nums[i];            int rem = Math.floorMod(sum, k);            if (firstIdx.containsKey(rem)) {                if (i - firstIdx.get(rem) >= 2) return true;            } else {                firstIdx.put(rem, i);            }        }        return false;    }
    public static void main(String[] args) {        System.out.println("Max equal 0/1 in [0,1,0,0,1,1,0]: "                + findMaxLengthEqual01(new int[]{0, 1, 0, 0, 1, 1, 0}));        System.out.println("[23,2,4,6,7] has len>=2 sum % 6 == 0: "                + checkSubarraySumMultipleOfK(new int[]{23, 2, 4, 6, 7}, 6));    }}
Output
Max equal 0/1 in [0,1,0,0,1,1,0]: 6
[23,2,4,6,7] has len>=2 sum % 6 == 0: true

What this code does

  • Mapping 0 -> -1 and 1 -> +1 turns 'equal number of 0s and 1s' into 'subarray sum == 0', so storing the earliest index of each balance finds the longest balanced subarray in O(n) time.
  • The same prefix-sum frequency map idea also returns for tree paths in Section 06.

In Subarray Sums Divisible by K, we want to count subarrays whose sum is a multiple of k (k > 0). By modular arithmetic: (P[right + 1] - P[left]) mod k == 0 ⇔ P[right + 1] mod k == P[left] mod k So two prefix sums form a subarray divisible by k if and only if they have the same remainder modulo k!

Crucial Java caveat: In Java, the % operator can return negative remainders when currSum < 0 (for example, -1 % 5 == -1, even though -1 and 4 are congruent modulo 5, since 4 - (-1) = 5). To normalize every remainder into 0 .. k - 1, always use: ``java int rem = ((currSum % k) + k) % k; // or Math.floorMod(currSum, k) ` And because remainders only lie in 0 .. k - 1, an int[k] array (with remCounts[0] = 1) replaces the HashMap`!

  • Two prefix sums have difference divisible by k iff their normalized remainders in 0..k-1 are equal.
  • In Java, normalize negative remainders with ((currSum % k) + k) % k or Math.floorMod(currSum, k).
  • Seed remCounts[0] = 1 for the empty prefix P[0] = 0.

Next step

Check your understanding

10 quick questions