Java Array Program · A39
Count Subarrays with Sum Equal to K in Java
A subarray from i to j sums to k exactly when prefix(j) - prefix(i - 1) = k. Count how many earlier prefixes equal prefix - k.
Problem Statement
Given an array of integers and a target k, return how many contiguous, non-empty subarrays have a sum equal to k.
The array may contain negative numbers and zeros, so a sliding window does not work.
Input/Output Examples
[2, 1, 3, -2, 4], k = 3Output2Explanation: [2, 1] and [3].[0, 0], k = 0Output3Explanation: [0] at index 0, [0] at index 1, and [0, 0].[5], k = 4Output0Explanation: the only subarray sums to 5.Visual Explanation
P - 3. That happens at P = 3 (prefix 0 seen) and P = 6 (prefix 3 seen).Seeding the map with prefix 0 counted once covers subarrays that start at index 0. Storing counts, not just presence, handles several earlier prefixes with the same value.
Approaches
The prefix-sum map is linear and works with negative numbers. The brute force tries every start.
Approach 1: Prefix Sums in a HashMap (Recommended)
Idea: keep how many times each prefix sum has occurred; at each index add the count of prefix - k.
- Put prefix 0 into the map with count 1.
- Add each value to the running prefix.
- Add
seen.getOrDefault(prefix - k, 0)to the answer. - Increase the count of the current prefix.
Time: O(n) · Space: O(n).
Approach 2: Every Start Position
Idea: for each start, extend to the right with a running sum and count matches.
- Loop over the start index.
- Extend the end, adding to a running sum.
- Count each time the sum equals
k.
Time: O(n²) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Prefix Sums in a HashMap (Recommended)
Looking up before inserting makes sure a subarray is never empty.
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class SubarraySumPrefixMap {
// A subarray ending here sums to k when some earlier prefix equals (prefix - k)
static int countSubarrays(int[] arr, int k) {
Map<Integer, Integer> seen = new HashMap<>();
seen.put(0, 1); // the empty prefix
int prefix = 0;
int count = 0;
for (int v : arr) {
prefix += v;
count += seen.getOrDefault(prefix - k, 0);
seen.merge(prefix, 1, Integer::sum);
}
return count;
}
public static void main(String[] args) {
Object[][] cases = {{new int[] {2, 1, 3, -2, 4}, 3}, {new int[] {0, 0}, 0}, {new int[] {5}, 4}};
for (Object[] c : cases) {
System.out.println(Arrays.toString((int[]) c[0]) + ", k=" + c[1] + " -> " + countSubarrays((int[]) c[0], (Integer) c[1]));
}
}
}
[2, 1, 3, -2, 4], k=3 -> 2 [0, 0], k=0 -> 3 [5], k=4 -> 0
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Every Start Position
Simple and reliable, used here to check the map version.
import java.util.Arrays;
public class SubarraySumBrute {
// Extends every start position to the right, keeping a running sum: O(n^2)
static int countSubarrays(int[] arr, int k) {
int count = 0;
for (int start = 0; start < arr.length; start++) {
int sum = 0;
for (int end = start; end < arr.length; end++) {
sum += arr[end];
if (sum == k) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
Object[][] cases = {{new int[] {2, 1, 3, -2, 4}, 3}, {new int[] {0, 0}, 0}, {new int[] {5}, 4}};
for (Object[] c : cases) {
System.out.println(Arrays.toString((int[]) c[0]) + ", k=" + c[1] + " -> " + countSubarrays((int[]) c[0], (Integer) c[1]));
}
}
}
[2, 1, 3, -2, 4], k=3 -> 2 [0, 0], k=0 -> 3 [5], k=4 -> 0
Time complexity: O(n²) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Prefix Sums in a HashMap | O(n) | O(n) |
| Every Start Position | O(n²) | O(1) |
Here n is the number of elements. The map version does one lookup and one update per element; the brute force considers all n(n + 1) / 2 subarrays.
Interview Tips and Recommended Approach
- Seed prefix 0. Without it, subarrays starting at index 0 are missed.
- Explain why a sliding window fails. Negative numbers mean the sum can shrink when the window grows.
- Store counts, not booleans. Several prefixes can have the same value.
- Know the variants: longest subarray with sum k, or sum divisible by k, use the same idea.
Recommended Approach: Prefix Sums in a HashMap
Why: it counts every matching subarray in one pass, works with negative values and is the core of a whole family of prefix-sum problems.