🌐 中文 English
This article aims to explain how to implement the underlying logic of the classic algorithm for subarray sum equals k. Problem link: https://leetcode.cn/problems/subarray-sum-equals-k/
Introduction
Subarray sum equals k is a classic problem. Its optimal solution is O(n), achieved using prefix sums + a hash table.
Implementation Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<unordered_map>
class Solution {
public:
unordered_map<int, int> map; // value in nums array, index in nums
int subarraySum(vector<int>& nums, int k) {
int n = nums.size();
int ans = 0;
int sum = 0;
map[0] = 1; // Initialize the count of prefix sum 0 as 1
for(int i = 0; i < n; ++i){
sum += nums[i];
if(map.count(sum - k) > 0){
ans += map[sum - k];
}
map[sum]++;
}
return ans;
}
};
Logic Explanation
- Use a hash table
mapto store the frequency of prefix sums. Initialize withmap[0] = 1, indicating that a prefix sum of 0 has occurred once (i.e., before adding any numbers). - Because the sum value is recorded via the map, it has a forward-propagating property, allowing the optimization of
vector<int> sumsto a singlesumvariable, reducing space complexity. - Use the hashmap to record the frequency of sum values. When
sum - kappears in the hashmap, it indicates the existence of a previous subarray whose sum equals k. - While traversing the array, calculate the current prefix sum
sumeach time, and check ifsum - kexists inmap. If it does, it means there is a subarray whose sum equalsk. Add the corresponding count to the answer, and record the current prefix sumsuminmap.
FAQ
Why does the same optimal solution code not outperform 100% of users?
When LeetCode’s backend executes your code, it may be assigned to different machines/containers. Factors like CPU load, cache, and memory usage can vary between machines, causing significant fluctuations in runtime for the same code across different submissions. This is why you might see large percentage variations (e.g., 92% → 99% → 84%) upon multiple submissions.
Summary
Using the prefix sum + hash table method, the subarray sum equals k problem can be solved in O(n) time complexity. This approach leverages the properties of prefix sums and the fast lookup capability of hash tables, making it a classic technique for solving such problems.