intermediate · prefix sums · hashing · counting
How many stretches add up to k?
Problem
Count the contiguous non-empty stretches of an integer array whose sum is exactly k. Values may be negative, so a sliding window does not work.
Constraints
- 0 ≤ n ≤ 32
- values from −99 to 99
- k from −999 to 999
Examples
[1, 2, 1, -1, 2], k = 3 → 3 — [1, 2], [2, 1] and [1, 2, 1, −1].
Show the solution
Prefix sums with a counting map
sum(i..j) = k exactly when prefix(i) = prefix(j + 1) − k. Counting earlier prefixes in a map answers that for every j at once.
Why it is correct
When processing position j, the map holds the count of every prefix(i) with i ≤ j, so adding count[prefix − k] counts exactly the stretches ending at j with sum k.
Complexity
Time O(n) expected, extra space O(n). One expected-O(1) lookup and one update per element.
For contrast: Sum every stretch with running sums. That costs O(n²) time and O(1) space.
Edge cases
- k = 0 with zeros in the array: every zero-sum stretch counts.
- Negative values: why a two-pointer window fails here.
- The initial {0: 1} counts stretches that start at index 0.
Common mistakes
- Forgetting the initial prefix 0.
- Updating the map before the lookup (counts empty stretches when k = 0).
Step through it
The solution in four languages
Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.
namespace Bekadan.Dsa.Examples.Problems;
public static class SubarraySumK
{
/// <summary>Number of non-empty contiguous stretches summing to k. Expected O(n) time, O(n) space.</summary>
public static int Count(int[] values, int k)
{
var seen = new Dictionary<int, int> { [0] = 1 }; // prefix sum -> times seen
int prefix = 0, result = 0;
foreach (int value in values)
{
prefix += value;
result += seen.GetValueOrDefault(prefix - k); // earlier prefixes that leave exactly k
seen[prefix] = seen.GetValueOrDefault(prefix) + 1;
}
return result;
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/SubarraySumK.cs
from collections.abc import Sequence
def count(values: Sequence[int], k: int) -> int:
"""Number of non-empty contiguous stretches summing to k. Expected O(n) time, O(n) space."""
seen = {0: 1} # prefix sum -> times seen
prefix = result = 0
for value in values:
prefix += value
result += seen.get(prefix - k, 0) # earlier prefixes that leave exactly k
seen[prefix] = seen.get(prefix, 0) + 1
return result
Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/subarray_sum_k.py
package dev.bekadan.dsa.problems;
import java.util.HashMap;
import java.util.Map;
public final class SubarraySumK {
private SubarraySumK() {
}
/** Number of non-empty contiguous stretches summing to k. Expected O(n) time, O(n) space. */
public static int count(int[] values, int k) {
Map<Integer, Integer> seen = new HashMap<>(Map.of(0, 1)); // prefix sum -> times seen
int prefix = 0, result = 0;
for (int value : values) {
prefix += value;
result += seen.getOrDefault(prefix - k, 0); // earlier prefixes that leave exactly k
seen.merge(prefix, 1, Integer::sum);
}
return result;
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/SubarraySumK.java
#pragma once
#include <span>
#include <unordered_map>
namespace bekadan::dsa::problems {
// Number of non-empty contiguous stretches summing to k. Expected O(n) time, O(n) space.
inline int subarray_sum_k(std::span<const int> values, int k) {
std::unordered_map<int, int> seen{{0, 1}}; // prefix sum -> times seen
int prefix = 0, result = 0;
for (int value : values) {
prefix += value;
if (auto it = seen.find(prefix - k); it != seen.end()) result += it->second; // earlier prefixes that leave exactly k
++seen[prefix];
}
return result;
}
} // namespace bekadan::dsa::problems
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/subarray_sum_k.hpp