Leetcode 560. Subarray Sum Equals K
Given an array of integers nums
and an integer k
, return the total number of continuous subarrays whose sum equals to k
.
Before we begin, let’s clarify a few points:
k
? (Return 0)To solve the problem efficiently, we need an algorithm that can compute the results in linear time, i.e., O(n). A brute-force approach would be to use nested loops to check all possible subarrays, which would result in O(n^2) time complexity. This is not optimal for larger inputs.
A more efficient approach leverages the concept of prefix sums and a hashmap to store the cumulative frequencies of the sums. Here is the strategy:
k
(i.e., current_sum - k
).k
.import java.util.HashMap;
import java.util.Map;
public class Solution {
public int subarraySum(int[] nums, int k) {
// HashMap to store (cumulative sum, frequency) pairs
Map<Integer, Integer> cumulativeSumFreq = new HashMap<>();
cumulativeSumFreq.put(0, 1); // Initialize with cumulative sum 0 having one occurrence
int cumulativeSum = 0;
int count = 0;
// Traverse through the array
for (int num : nums) {
cumulativeSum += num; // Update the cumulative sum
// Calculate the complement which when combined with the previous sums would reach k
int complement = cumulativeSum - k;
// If complement is found in the map, increment the count by the frequency of the complement
if (cumulativeSumFreq.containsKey(complement)) {
count += cumulativeSumFreq.get(complement);
}
// Update the cumulative sum frequency in the map
cumulativeSumFreq.put(cumulativeSum, cumulativeSumFreq.getOrDefault(cumulativeSum, 0) + 1);
}
return count;
}
}
This solution is efficient and handles large inputs within a reasonable time frame.
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?