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.

Input: nums = [1, 1, 1], k = 2
Output: 2
Explanation:
one contiguous subarray is from index 0-1 [1, 1]
second contiguous subarray is from index 1-2 [1, 1]
Input: nums = [1, 2, 3], k = 3
Output: 2
Input: nums = [1, -1, 1], k = 1
Output: 3
Explanation:
one contiguous subarray at index 0 [1]
second contiguous subarray is from index 0-2 [1, -1, 1]
third contiguous subarray at index 2 [1]
Constraints:

Contents

As per the problem statement, one of the key point to remember is that the input array can contain negative numbers, so we have to find continuous subarrays that includes negative numbers too for example if the k=1 and input array is [1, -1, 1] then subarrays with [1] as well as [1, -1, 1] will give sum of 1.

In this approach, we will first compute a prefix sum array, then we create a HashMap to store the mapping of prefix - k to it's count of how many times have this number appeared and if the number appeared add it to the result.
The main idea is if we find the prefix -k in the map that means there is a subarray from the index where this found (exclusive) and the current prefix.

Example:

Lets look at an example with input array [1, 2, 3, 4, 5] and k = 9, by looking at the aray we can see there are two contiguous subarrays [2, 3, 4] and [4, 5], let's apply the steps on this input.

import java.util.HashMap; public class SubarraysSumEqualToK { static int subarraySum(int[] nums, int k) { int result = 0; int[] prefixSum = new int[nums.length]; prefixSum[0] = nums[0]; for(int i=1; i<nums.length; i++) { prefixSum[i] = nums[i] + prefixSum[i-1]; } HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, 1); for(int prefix: prefixSum) { if(map.containsKey(prefix-k)) { result += map.get(prefix-k); } map.merge(prefix, 1, Integer::sum); } System.out.println(map); return result; } public static void main(String[] args) { System.out.println(subarraySum(new int[]{1,-1,1}, 1)); System.out.println(subarraySum(new int[]{1,2,3,4,5}, 9)); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of nums array.
Space complexity: O(n), since we are creating prefix sum array with size n and a HashMap to keep the counts.

Above implementations source code can be found at GitHub link for Java code