Browse Curriculum
Prefix Sum
Medium

Subarray Sum Equals K

Find number of subarrays with sum K.

Problem Understanding

Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

Strategy (HashMap + Prefix Sum)

We want Sum(i, j) == k.
Since Sum(i, j) = Prefix[j] - Prefix[i-1], we want:
Prefix[j] - Prefix[i-1] == k
=> Prefix[i-1] == Prefix[j] - k.

Algorithm:

  • Iterate through array, maintaining current_sum.

  • Check HashMap: how many times have we seen current_sum - k before?

  • Add that count to our answer.

  • Add current_sum to the HashMap.

Interactive Visualization

Step 1 / 1

Initializing...

1x

Visualize how prefix sums accumulate. In this problem, we look back to find if (CurrentSum - k) occurred before.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.