560. Subarray Sum Equals K
LeetCode 560. Subarray Sum Equals K
Description
Given an array of integers nums
and an integer k
, return the total number of continuous subarrays whose sum equals tok
.
Example 1:
Example 2:
Constraints:
1 <= nums.length <= 2 * 10^4
-1000 <= nums[i] <= 1000
-10^7 <= k <= 10^7
Tags
Array, Hash Table
Solution
This is a classic prefix-sum problem. To obtain the left and right bound of a subarray whose sum is k
, we can find 2 prefix-sum who meet the condition .
In terms of implementation, we build a map m
whose key is sum of first n
numbers and value is the occurrences of this sum, initialized with {0: 1}
. Then we iterate over nums
, and:
calculate prefix-sum
preSum
;update the counter of subarrays whose sum equals to
k
, by addingm[preSum-k]
onto it;add
m[preSum]
by 1.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?