You are given an array of integers nums and an integer k. Your task is to find the total number of continuous subarrays whose sum equals to k.
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^7Can the input array contain negative numbers? Yes, the array can contain negative numbers.
Can the input array be empty?
No, the length of nums is at least 1 according to the constraints.
Is there a maximum length to the input array?
Yes, the maximum length is 2 * 10^4.
Should the subarrays be contiguous? Yes, the subarrays must be continuous.
To efficiently solve this problem, we can use a hashmap (dictionary) to store the cumulative sums (prefix sums) and their frequencies as we iterate through the array. The key idea is:
current_sum is the cumulative sum up to the current index.current_sum - k exists in the hashmap, it means there is a subarray ending at the current index which sums to k.Here is the step-by-step approach:
current_sum to 0.prefix_sums to store the frequencies of cumulative sums. Initially, set prefix_sums[0] = 1 because a sum of 0 means there’s a subarray from the start that sums to k.current_sum.current_sum - k is in prefix_sums. If it is, it means there are prefix_sums[current_sum - k] subarrays ending at this index which sum to k.current_sum.def subarraySum(nums, k):
count = 0
current_sum = 0
prefix_sums = {0: 1}
for num in nums:
current_sum += num
# Check if there is a prefix sum that, when removed from current_sum, equals k
if current_sum - k in prefix_sums:
count += prefix_sums[current_sum - k]
# Update the hashmap with the current sum
if current_sum in prefix_sums:
prefix_sums[current_sum] += 1
else:
prefix_sums[current_sum] = 1
return count
nums array, and each operation (updating and checking in the hashmap) is O(1).The above solution efficiently computes the total number of continuous subarrays whose sum equals k within optimal time and space constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?