Count subarrays whose sum equals K. Show brute force, prefix sums and the HashMap of prefix sums.
Problem
nums = [1, 1, 1], k = 2 → 2. nums = [3, 4, 7, 2, -3, 1, 4, 2], k = 7 → 4. Negative numbers are allowed, which rules out a simple sliding window.
Pattern
Prefix sum + HashMap. sum(i..j) = prefix[j] - prefix[i - 1], so a subarray ending at j sums to k exactly when an earlier prefix equals prefix[j] - k. Count how many times each prefix has occurred.
Approach 1: All subarrays with a running sum (feasible, O(n²))
class SubarraySumBrute {
static int count(int[] nums, int k) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
int sum = 0;
for (int j = i; j < nums.length; j++) {
sum += nums[j];
if (sum == k) count++;
}
}
return count;
}
}Approach 2: Prefix sum array, still O(n²)
Clearer about the idea, same complexity.
class SubarraySumPrefix {
static int count(int[] nums, int k) {
int n = nums.length, count = 0;
int[] prefix = new int[n + 1];
for (int i = 0; i < n; i++) prefix[i + 1] = prefix[i] + nums[i];
for (int start = 0; start < n; start++)
for (int end = start + 1; end <= n; end++)
if (prefix[end] - prefix[start] == k) count++;
return count;
}
}Approach 3: HashMap of prefix-sum frequencies (O(n)) — optimal
import java.util.HashMap;
import java.util.Map;
class SubarraySumHashMap {
static int count(int[] nums, int k) {
Map<Integer, Integer> seen = new HashMap<>();
seen.put(0, 1); // empty prefix: subarrays starting at index 0
int sum = 0, count = 0;
for (int x : nums) {
sum += x;
count += seen.getOrDefault(sum - k, 0); // earlier prefixes that make a k-sum ending here
seen.merge(sum, 1, Integer::sum);
}
return count;
}
}
class SubarraySumDemo {
public static void main(String[] args) {
int[] a = {3, 4, 7, 2, -3, 1, 4, 2};
System.out.println(SubarraySumBrute.count(a, 7) + " " + SubarraySumPrefix.count(a, 7) + " " + SubarraySumHashMap.count(a, 7)); // 4 4 4
System.out.println(SubarraySumHashMap.count(new int[] {1, 1, 1}, 2)); // 2
}
}Feasible → optimal
O(n²) by enumerating subarrays (with or without a prefix array) → O(n) time, O(n) space with a HashMap of prefix counts. The sliding window does not work here because negative numbers break the "shrink when too big" rule.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related (same pattern): longest subarray with sum K.
Store the first index where each prefix sum occurs (putIfAbsent(sum, i)); for each j, if sum - k was seen at index i, the length is j - i. O(n). Special case: longest subarray with equal 0s and 1s, by mapping 0 → -1 and looking for sum 0.
Related (same pattern): count subarrays whose sum is divisible by K.
Use prefix sums modulo k (normalise negatives with ((sum % k) + k) % k); two prefixes with the same remainder bound a subarray divisible by k, so add count[remainder] before incrementing it. O(n) time, O(k) space.
Related (same pattern): find the majority element (appears more than n/2 times).
HashMap counting is O(n) time and O(n) space; groupingBy(identity, counting()) is the streams version; sorting and taking the middle element is O(n log n); Boyer–Moore voting (keep a candidate and a counter, increment on match, decrement otherwise, switch candidate at zero) is O(n) time and O(1) space, the optimal answer.