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 * 104-1000 <= nums[i] <= 1000-107 <= k <= 107When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a long row of numbered boxes and you want to find every possible consecutive group of boxes whose numbers add up to a specific target sum. The brute force approach simply investigates every single possible starting point and ending point to check every combination one by one.
Here's how the algorithm would work step-by-step:
def subarray_sum(numbers, target_sum):
matching_subarrays_count = 0
# Iterate through every possible starting position to ensure all subarrays are tested
for start_index in range(len(numbers)):
current_subarray_sum = 0
# Expand the subarray one box at a time to check the cumulative sum sequentially
for end_index in range(start_index, len(numbers)):
current_subarray_sum += numbers[end_index]
# Compare the accumulated sum against the target to count valid subarrays
if current_subarray_sum == target_sum:
matching_subarrays_count += 1
return matching_subarrays_countInstead of checking every single possible grouping of numbers, the optimal approach keeps a running total of the numbers as we encounter them. By keeping track of how often each running total has appeared in the past, we can instantly spot hidden sections that add up to our target.
Here's how the algorithm would work step-by-step:
def subarray_sum(nums, target_k):
running_tally = 0
matching_sections_count = 0
tally_frequency_map = {0: 1}
# Check if a past tally exists whose difference with current tally equals target.
for number in nums:
running_tally += number
needed_past_tally = running_tally - target_k
if needed_past_tally in tally_frequency_map:
matching_sections_count += tally_frequency_map[needed_past_tally]
# Record current running tally into memory so future steps can look back at it.
if running_tally in tally_frequency_map:
tally_frequency_map[running_tally] += 1
else:
tally_frequency_map[running_tally] = 1
return matching_sections_count| Case | How to Handle |
|---|---|
| Empty array nums with any value of k | The prefix sum map initialized with zero count ensures the loop returns zero without throwing errors. |
| Array containing a single element equal to k | The running prefix sum equals k and the pre-existing base entry of {0: 1} increments the count to one. |
| Array containing a single element not equal to k | The running prefix sum does not match k minus any previous sum, resulting in a return value of zero. |
| Array with negative numbers and zeros mixed in | Prefix sum logic naturally handles negative increments and zero values because sums are not strictly increasing. |
| Multiple subarrays sharing overlapping ranges summing to k | Storing prefix sum frequencies in a hash map accurately counts every valid starting point for each ending point. |
| No subarray sums up to k | The total count remains at its initial value of zero and returns correctly after traversing the array. |
| Maximum sized inputs up to the constraints limit | An O(n) linear scan using a hash map processes the entire array efficiently within standard time limits. |
| Large cumulative sums causing potential integer overflow | Using standard 64-bit integer types for the running sum prevents overflow issues during extreme summation. |