Command Palette

Search for a command to run...

← All patterns

Pattern · Hashing & Counting

Prefix Sum + Hash Map

Count subarrays with a target sum by remembering how often each running total has appeared.

Time O(n) · Space O(n)

Taught in Module 5: Prefix Sum

Think of it like this

Checking a bank statement for any stretch of days that added exactly ₹500: if today's balance minus ₹500 was ever a past balance, that stretch exists.

Clues that point here

  • → "Number of subarrays with sum K"
  • → Negative numbers allowed (so sliding window fails)
  • → Subarray sum divisible by K
  • → Longest subarray with equal 0s and 1s

Not this pattern when

  • ✕ All numbers are positive and you need the shortest/longest window (sliding window is simpler)

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Prefix Sum + Hash Map · template
Map<Integer, Integer> seen = new HashMap<>();
seen.put(0, 1);                          // empty prefix: sum 0 seen once
int sum = 0, count = 0;
for (int x : arr) {
    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;

Common versions

  • Subarray sum equals K
  • Continuous subarray sum (mod K)
  • Contiguous array (0s and 1s)
  • Count subarrays with an odd sum

Practice problems with this pattern

Related patterns