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.
An integer x
is a multiple of k
if there exists an integer n
such that x = n * k
. 0
is always a multiple of k
.
k
is zero?
k
is zero, we need to check if there is a subarray whose sum is zero, which is a special case.To solve this problem efficiently:
k
.k
.sum(i) % k == sum(j) % k
where i < j
, then the subarray sum from i+1
to j
is a multiple of k
.import java.util.HashMap;
public class ContinuousSubarraySum {
public boolean checkSubarraySum(int[] nums, int k) {
HashMap<Integer, Integer> remainderMap = new HashMap<>();
// Initialize with remainder 0 at index -1 to handle subarray starting from index 0
remainderMap.put(0, -1);
int currentSum = 0;
for (int i = 0; i < nums.length; i++) {
currentSum += nums[i];
int remainder = (k == 0) ? currentSum : currentSum % k;
// Fix for negative remainders
if (remainder < 0) {
remainder += k;
}
if (remainderMap.containsKey(remainder)) {
if (i - remainderMap.get(remainder) > 1) {
return true;
}
} else {
remainderMap.put(remainder, i);
}
}
return false;
}
public static void main(String[] args) {
ContinuousSubarraySum solution = new ContinuousSubarraySum();
// Example Test Cases
int[] nums1 = {23, 2, 4, 6, 7};
int k1 = 6;
System.out.println(solution.checkSubarraySum(nums1, k1)); // Expected output: true
int[] nums2 = {23, 2, 6, 4, 7};
int k2 = 6;
System.out.println(solution.checkSubarraySum(nums2, k2)); // Expected output: true
int[] nums3 = {23, 2, 6, 4, 7};
int k3 = 13;
System.out.println(solution.checkSubarraySum(nums3, k3)); // Expected output: false
}
}
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?