Browse Curriculum
Prefix Sum
Medium
Subarray Sum Equals K
Find number of subarrays with sum K.
10 min read
Solve on LeetCodeProblem 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 - kbefore?Add that count to our answer.
Add
current_sumto 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.
ON THIS PAGE
- Problem Understanding
- Strategy (HashMap + Prefix Sum)
- Interactive Visualization
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.
