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
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Strategy (HashMap + Prefix Sum)
- Interactive Visualization
- Edge Cases
- Complexity Analysis
- Dry Run
- Solution
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.
