523. Continuous Subarray Sum #160
-
Topics: Given an integer array nums and an integer k, return A good subarray is a subarray where:
Note that:
Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to check whether there is a subarray of at least two elements whose sum is a multiple of Key Observations:
Solution Strategy:
Let's implement this solution in PHP: 523. Continuous Subarray Sum <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Boolean
*/
function checkSubarraySum($nums, $k) {
// Initialize a hashmap to store the remainder of prefix sums
$mod_map = array(0 => -1); // Initialize with 0 mod value at index -1 for convenience
$sum = 0;
// Iterate through the array
for ($i = 0; $i < count($nums); $i++) {
$sum += $nums[$i];
// Calculate the remainder of the sum when divided by k
if ($k != 0) {
$sum %= $k;
}
// If the same remainder has been seen before, we have a subarray sum that is divisible by k
if (isset($mod_map[$sum])) {
// Ensure the subarray length is at least 2
if ($i - $mod_map[$sum] > 1) {
return true;
}
} else {
// Store the index of this remainder in the hashmap
$mod_map[$sum] = $i;
}
}
// No such subarray found
return false;
}
// Example 1
$nums = [23, 2, 4, 6, 7];
$k = 6;
echo checkSubarraySum($nums, $k) ? 'true' : 'false'; // Output: true
// Example 2
$nums = [23, 2, 6, 4, 7];
$k = 6;
echo checkSubarraySum($nums, $k) ? 'true' : 'false'; // Output: true
// Example 3
$nums = [23, 2, 6, 4, 7];
$k = 13;
echo checkSubarraySum($nums, $k) ? 'true' : 'false'; // Output: false
?> Explanation:
Time Complexity:
This solution is efficient and works within the problem's constraints. |
Beta Was this translation helpful? Give feedback.
We need to check whether there is a subarray of at least two elements whose sum is a multiple of
k
.Key Observations:
Modulo Property:
The sum of a subarray can be reduced to the remainder (modulo
k
). Specifically, for any two indicesi
andj
(wherei < j
), if the prefix sumsprefix_sum[j] % k == prefix_sum[i] % k
, then the sum of the subarray betweeni+1
andj
is a multiple ofk
. This is because the difference between these prefix sums is divisible byk
.HashMap for Prefix Modulo:
We'll store the modulo values of prefix sums in a hash table (or associative array). If the same modulo value repeats at a later index, it means the subarray sum between these indices is divisible by
k
.H…