Skip to main content

Subarray Sum Equals K


Subarray Sum Equals K: Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:
Input: nums = [1,1,1], k = 2
Output: 2

Example 2:
Input: nums = [1,2,3], k = 3
Output: 2

Constraints:
  • 1 <= nums.length <= 2 * 10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7

Try this Problem on your own or check similar problems:

  1. Continuous Subarray Sum
  2. Subarray Product Less Than K
  3. Subarray Sums Divisible by K
  4. Minimum Operations to Reduce X to Zero
Solution:
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
int count = 0, sum = 0;

for(int i = 0; i < nums.length; ++i){
sum += nums[i];
count += map.getOrDefault(sum - k, 0);
map.put(sum, map.getOrDefault(sum, 0) + 1);
}

return count;
}

Time/Space Complexity:
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Explanation:

The problem is based on prefix sum Range Query Sum Immutable rule, if we have difference k between sum ending at index i and sum ending at index j we know that elements between those indices form a subarray with sum k. We use the map to count number of times prefixSum appears (it can appear more than once when hit index i) and increase the count accordingly. The space and time complexity are linear and proportional to the input array size. One thing to note that at beginning we have prefixSum 0 since we can have first few numbers forming a prefixsum k when we search in the map for k-k=0 we should find 0 prefixSum at least once for the first subarray with sum k.