← All Patterns

Pattern Recognition Drill

#28

Medium Hash Maps

The Problem

Count subarrays whose elements sum to exactly k.

What approach would you use?

Think about it before scrolling down.

Subarray sum equals k

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 →