Subarray Sum Equals K
mediumSave
ArrayHash TablePrefix Sum
Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.
Example 1
Input
[ [ 1, 1, 1 ], 2 ]
Output
2
Explanation. There are two subarrays that add up to 2: [1, 1] and another [1, 1].
Example 2
Input
[ [ 1, 2, 3 ], 3 ]
Output
2
Explanation. The subarrays [1, 2] and [3] sum to 3.
Example 3
Input
[ [ 1, -1, 0 ], 0 ]
Output
3
Explanation. The subarrays [1, -1], [0], and [1, -1, 0] sum to 0.
Follow-up: Try to come up with an algorithm with a better than O(n^2) time complexity.
Constraints:
1. The length of `nums` is in the range [1, 20,000].\n2. The range of numbers in the array is between -1000 and 1000.\n3. The value of `k` is between -1,000,000 and 1,000,000.
- Views
- 3