Leetcode 523. Continuous Subarray Sum
Given an integer array nums
and an integer k
, return true
if nums
has a continuous subarray of size at least two whose elements sum up to a multiple of k
, or false
otherwise.
A continuous subarray is defined as a non-empty sequence of elements of the array in the order they occur.
What should we do if k
is zero?
If k
is zero, it means we are looking for any subarray whose sum is zero.
Can negative numbers be present in nums
?
Yes, the array can have negative, zero, and positive integers.
What’s the size range of nums
and the possible values of k
?
The length of the array nums
will be in the range [1, 10^5]
, and the integer k
will be in the range [-10^9, 10^9]
including zero.
prefix_sum[i]
and prefix_sum[j]
such that (prefix_sum[j] - prefix_sum[i]) % k == 0
, then the sum of the elements between i+1
and j
is a multiple of k
.k
.-1
to handle cases where the prefix sum itself is a multiple of k
.k
.true
.% k
.k
is zero, check if there are at least two consecutive zeroes.#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool checkSubarraySum(vector<int>& nums, int k) {
unordered_map<int, int> remainder_index_map;
remainder_index_map[0] = -1; // to handle cases where the sum itself is a multiple of k
int running_sum = 0;
for (int i = 0; i < nums.size(); ++i) {
running_sum += nums[i];
int remainder = (k == 0) ? running_sum : running_sum % k;
// Adjust for negative remainder
if (remainder < 0) remainder += k;
if (remainder_index_map.find(remainder) != remainder_index_map.end()) {
if (i - remainder_index_map[remainder] > 1) {
return true;
}
} else {
remainder_index_map[remainder] = i;
}
}
return false;
}
};
n
is the size of the input array nums
. This is due to a single pass through the array.n
elements (though in practice, often fewer).This approach efficiently checks for any continuous subarray whose sum is a multiple of k
by leveraging the properties of the remainder operation and utilizing a hashmap to track remainders of prefix sums.
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?