#560

Subarray Sum Equals K

Medium Prefix sum + HashMap

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count the contiguous subarrays whose elements add up to exactly k. Values can be negative.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: count contiguous pieces that add to exactly k (negatives allowed).

Why this works: a piece from i+1 to j sums to k when prefix[j] - prefix[i] = k. So at each j, count earlier prefixes equal to prefix[j] - k, using a HashMap.

Example: nums = [1, 1, 1], k = 2

map {0:1}sum 1: need -1 → 0;  map {0:1, 1:1}sum 2: need 0  → +1; map {…, 2:1}sum 3: need 1  → +1answer 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting the {0: 1} entry, which misses every subarray starting at index 0.