Subarray Sum Equals K
Master this topic with zero to advance depth.
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
The subarrays [1,1] and [1,1] have sum 2.
The subarrays [1,2] and [3] have sum 3.
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.
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) |
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.
Detailed Dry Run
| i | j | Running Sum | k=2? |
|---|---|---|---|
| 0 | 0 | 1 | No |
| 0 | 1 | 2 | Yes |
| 0 | 2 | 3 | No |
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.
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 |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.