Subarray Sum Equals K
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Arrays & Hashing.
Subarray Sum Equals K
The sum of subarray
nums[i...j] is PrefixSum[j] - PrefixSum[i-1]. If this difference equals k, then PrefixSum[j] - k = PrefixSum[i-1]. We use a HashMap to count occurrences of PrefixSum[i-1].Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array.
Visual Representation
nums = [1, 2, 3], k = 3
Subarrays:
[1, 2] -> Sum = 3 (Valid)
[3] -> Sum = 3 (Valid)
Answer: 2Examples
Input: nums = [1,1,1], k = 2
Output: 2
The subarrays [1,1] and [1,1] have sum 2.
Input: nums = [1,2,3], k = 3
Output: 2
The subarrays [1,2] and [3] have sum 3.
Approach 1
Level I: Brute Force (All Subarrays)
Intuition
We check every possible subarray by iterating through all pairs of start indices
i and end indices j. For each pair, we calculate the sum of elements from i to j. If the sum equals k, we increment our count.⏱ O(N²) after optimizing the inner sum loop.💾 O(1) extra space.
Detailed Dry Run
| i | j | Subarray | Sum | Count |
|---|---|---|---|---|
| 0 | 0 | [1] | 1 | 0 |
| 0 | 1 | [1, 1] | 2 | 1 (k=2) |
| 1 | 1 | [1] | 1 | 1 |
| 1 | 2 | [1, 1] | 2 | 2 (k=2) |
Approach 2
Level II: Better Solution (Cumulative Sum O(N²))
Avoid the inner sum loop by adding
nums[j] to the current running sum as you expand the subarray.⏱ O(N²)💾 O(1)
Detailed Dry Run
| i | j | Running Sum | k=2? |
|---|---|---|---|
| 0 | 0 | 1 | No |
| 0 | 1 | 2 | Yes |
| 0 | 2 | 3 | No |
Approach 3
Level III: Optimal Solution (Prefix Sum + HashMap)
Intuition
The sum of subarray
nums[i...j] is PrefixSum[j] - PrefixSum[i-1]. If this difference equals k, then PrefixSum[j] - k = PrefixSum[i-1]. We use a HashMap to store the frequencies of prefix sums encountered so far. For each new PrefixSum[j], we check how many times PrefixSum[j] - k has appeared before.⏱ O(N) single pass traversal.💾 O(N) to store prefix sums in the map.
Detailed Dry Run
Prefix Sum Visual
nums = [1, 2, 3], k = 3
Initial Map: {0: 1} (Subarray with sum 0 starts from beginning)| Index | Num | Current Prefix Sum (S) | Target (S - k) | Found in Map? | New Map State | Count |
|---|---|---|---|---|---|---|
| 0 | 1 | 1 | -2 | No | {0:1, 1:1} | 0 |
| 1 | 2 | 3 | 0 | Yes (freq 1) | {0:1, 1:1, 3:1} | 1 |
| 2 | 3 | 6 | 3 | Yes (freq 1) | {0:1, 1:1, 3:1, 6:1} | 2 |
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.