560. Subarray Sum Equals K Medium
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
Approach
Input: An integer array nums, and an integer k
Output: Return the number of subarrays summing to k
This problem belongs to the Prefix Sum + Hash Map category.
We need to maintain the following three variables:
total: The current prefix sum up to the traversal point;count: The number of subarrays satisfying the condition;prefix_map: A hash map used to record the number of times each prefix sum has occurred.
As we iterate through the array, we accumulate the prefix sum total. We then check if total - k exists in our prefix_map:
If it does exist, it means that at some point earlier, the prefix sum was exactly total - k. The sum of the subarray from that point up to the current element is exactly k;
We add the corresponding occurrence count of total - k to our result count;
Finally, we record the frequency of the current prefix sum total in the hash map to be used in future iterations.
Implementation
from typing import List
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
total = 0 # Current prefix sum
count = 0 # Quantity of subarrays satisfying condition parameters natively
prefix_map = {0: 1} # Hash Map: key=prefixSum, value=frequency occurrences natively matching
# Initially set to {0: 1}, mapping 1 case for an empty subarray parameter matching exactly evaluated counts securely
for num in nums:
total += num # Accumulate current element resolving prefix metric variables cleanly functionally executing accurately mathematically
# Validate mappings searching historical sequences returning required properties securely validating logical metric values checking securely natively appropriately cleanly effectively evaluated constraints
if total - k in prefix_map:
count += prefix_map[total - k] # Increment total mapping outcomes bounding properties dynamically measuring matching appropriately
# Overwrite current properties executing mappings dynamically counting frequencies matching mathematically
prefix_map[total] = prefix_map.get(total, 0) + 1
return count # Finalize evaluated counts bounding uniquely checking successfully satisfying parameters reliablyconst subarraySum = function(nums, k) {
// Current prefix sum
let total = 0;
// Condition matched evaluating instances
let count = 0;
// Key mappings defining prefix bounds sequentially parsed logically executing maps occurrences efficiently tracking subsets reliably safely natively checking properties
// Default starting node properties mapped efficiently capturing initial prefix counts mathematically
let prefix_map = {0: 1};
for (let num of nums) {
// Accumulate mapped limits effectively evaluating variables functionally
total += num;
// Retrieve properties tracking prefix maps parsing optimally testing limits mapped successfully dynamically mapping subsets accurately
if (prefix_map[total - k]) {
// Stack instances passing variables reliably logging metrics uniquely parsing logically validating metrics checking counts securely
count += prefix_map[total - k];
}
// Increment current prefix logs validating mapping properties testing variables resolving bounds appropriately sequentially
prefix_map[total] = (prefix_map[total] || 0) + 1;
}
// Results calculated parsing sequences executing matching arrays perfectly securely evaluating bounds reliably uniquely optimally smoothly logically perfectly
return count;
};Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
Links
560. Subarray Sum Equals K (English)560. 和为 K 的子数组 (Chinese)