30. Subarray Sum Equals K
Count every continuous range of array positions whose values add up exactly to k. Negative values and zeros are permitted, so increasing a range does not necessarily increase its sum.
Two ranges at different positions count as different answers even if their values are identical. Count overlapping ranges separately as well.
Example 1
Input
[1,1,1], k=2
Output
2
Explanation: Intervals [0,1] and [1,2] each sum to two.
Example 2
Input
[0,0], k=0
Output
3
Explanation: Both singletons and the length-two interval count.
Example 3
Input
[1,-1,1], k=1
Output
3
Explanation: The two 1 singletons and the full interval count; shrinking a positive-sum window is not generally valid.
Constraints
0 <= nums.length <= 105-231 <= nums[i] <= 231 - 1-1014 <= k <= 1014
Hints
Hint 1
Express a subarray sum as two prefix sums.
Hint 2
Which earlier prefix value would make their difference equal k?
Hint 3
Count earlier occurrences, seed zero once, and query before inserting.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Repeated zero prefixes
[0,0]
0
3