Leetcode 560. Subarray Sum Equals K
Given an array of integers nums
and an integer k
, you need to find the total number of continuous subarrays whose sum equals to k
.
To solve the problem, we can use a hashmap (unordered_map in C++) to keep track of the cumulative sums and their frequencies. This will help us efficiently calculate the number of subarrays that sum up to k
.
Here is the step-by-step approach:
sum
to 0, which will keep track of the cumulative sum while iterating through the array.count
to 0, which will store the count of subarrays that sum to k
.k
exists in the hashmap. If it does, it means there is a subarray ending at the current index with a sum of k
.k
.#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> cumulativeSumFreq; // To store cumulative sum and its frequency
cumulativeSumFreq[0] = 1; // To account for subarrays that begin at the start of the array
int sum = 0;
int count = 0;
for (const int& num : nums) {
sum += num;
// Check if there is a subarray summing to k
if (cumulativeSumFreq.find(sum - k) != cumulativeSumFreq.end()) {
count += cumulativeSumFreq[sum - k];
}
// Update the frequency of the current cumulative sum
cumulativeSumFreq[sum]++;
}
return count;
}
};
int main() {
Solution sol;
vector<int> nums = {1, 1, 1};
int k = 2;
cout << sol.subarraySum(nums, k) << endl; // Output: 2
return 0;
}
n
is the number of elements in the array. We iterate through the array only once.This approach captures the essence of leveraging prefix sums and hash maps to maintain constant look-up times, resulting in a highly efficient solution.
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?