Medium
Subarray Sum Equals K
- Time limit
- 2 s
- Memory limit
- 256 MB
- Estimated
- 20 min
- Prefix Sums and Difference Arrays
Description
Description
Given an integer array nums and an integer k, return the number of contiguous subarrays whose elements sum to exactly k.
Examples
Example 1
- Input:
nums = [1, 1, 1], k = 2 - Output:
2
Example 2
- Input:
nums = [1, 2, 3], k = 3 - Output:
2 - Explanation: The subarrays
[1, 2]and[3]both sum to3.
Example 3
- Input:
nums = [1, -1, 0], k = 0 - Output:
3
Expected Function Behavior
Implement subarraySum(nums, k) and return the count of matching subarrays.
Constraints
1 <= nums.length <= 20000-1000 <= nums[i] <= 1000-1000000000 <= k <= 1000000000
Sample cases
3Sample 1
Input
k = 2 nums = [1,1,1]
Expected output
2
Sample 2
Input
k = 3 nums = [1,2,3]
Expected output
2
Skills and languages
Patterns
- Prefix Sum with Hash Map
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer