Subarray Sum Equals K
Problem
Read an array and a number k. Print how many continuous subarrays have the sum k. The numbers can be negative.
Constraints
- 1 <= n <= 10^5
Examples
Input
3 1 1 1 2
Output
2
Solutions
The sum of a subarray is the difference of two prefix sums. For each end position we look up how many earlier prefix sums equal prefix - k. A sliding window does not work here, because negative numbers break its logic.
/*
* Problem : Process an array and a number k.
* Input : n, integers, then k.
* Output : The number of subarrays.
* Approach: Prefix sums and a map.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(int[] a, int k) {
// Step 1: seen counts how many earlier prefix sums have each value. The empty prefix has the sum 0.
java.util.Map<Long, Integer> seen = new java.util.HashMap<>();
seen.put(0L, 1);
long prefix = 0;
int count = 0;
for (int value : a) {
// Step 2: The prefix sum up to this element.
prefix += value;
// Step 3: A subarray ending here has the sum k if some earlier prefix sum is prefix - k.
count += seen.getOrDefault(prefix - k, 0);
// Step 4: Remember this prefix sum.
seen.put(prefix, seen.getOrDefault(prefix, 0) + 1);
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
int k = scanner.nextInt();
System.out.println(solve(a, k));
}
}
Hints (2)
- How is a subarray sum written with two prefix sums?
- Why does the sliding window fail with negative numbers?