Given an array of integers
A subarray is a contiguous
Output: 2
Explanation:
one contiguous subarray is from index 0-1
second contiguous subarray is from index 1-2
Output: 2
Output: 3
Explanation:
one contiguous subarray at index 0
second contiguous subarray is from index 0-2
third contiguous subarray at index 2
Constraints:
1 <= nums.length <= 2 * 104 -1000 <= nums[i] <= 1000 -107 <= k <= 107
Contents
Solution 1 - Create prefix sum array and then find if there is a possible continuous subarray with K sum
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
In this approach, we will first compute a
The main idea is if we find the
Example:
Lets look at an example with input array
-
First, lets compute the prefix sum array using:
preffixSum[i] = nums[i] + (i==0 ? 0 : preffixSum[i-1]); So, the prefix sum array will be[1, 3, 6, 10, 15] -
Next, we will create a
HashMap to storeprefix -k and store the count as 1, or if it already exists then increment the count.-
If we find
prefix -k in the array, that means the sub array where the index of this value started (exclusive), and until the current prefix it is a contiguous subarray. In the above example, at index3 in prefix sum we have value10 soprefix-k will be1 and this value is at index0 , so that means there is a sub array from index1 to index3 in the original array. [2, 3, 4] -
Similarly, at index at index
4 in prefix sum we have value15 soprefix-k will be6 and this value is at index2 , so that means there is a sub array from index3 to index4 in the original array. [4, 5]
Also, store 0 as key and1 as value, because, if the sumk starts from index 0. The reason we need to do this is because, if the sumk includes the0th index in input array, for examplenums = [1, -1, 1] and k=1 , here first element in array is 1, andk- prefix will be0 . So, to account this we will store with 0, there will be always 1 answer. -
If we find
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(n), since we are creating prefix sum array with size
Above implementations source code can be found at