subarray-sum-equals-k
Problem
Problem Description
Solution
Usually when see subarray sum relate problem, preSum should come to your mind. calculate all subarray sum = k, using map to keep track of number of times presum already appear, for each presum, check whether presum - k in map or not:
if
map.containsKey(presum - k)
, meaning presum already appear before,count+=map.get(presum-k);
then add/update map,
map.put(presum, map.getOrDefault(presum, 0) + 1)
after sum the whole array, return count.
For example:
Complexity Analysis
Time Complexity: O(N)
Space Complexity: O(N)
N - the length of array nums
Code
Last updated