← Prefix Sum

Pattern Recognition Drill

#28 — Subarray sum equals k

Medium Hash Maps

The Problem

Count subarrays whose elements sum to exactly k.

What approach would you use?

Think about it before scrolling down.

Key Signals

Prefix Sum

Running prefix sum + hash map counting. For each prefix[j], count of prefix[j]-k seen so far. O(n).

Alt: Hash Map

The hash map IS the core of the solution — combined with prefix sums.

Common Trap

Sliding window doesn't work here because elements can be negative. Prefix sum + hash map is needed.

← #27 #29 →