974. Subarray Sums Divisible by K #202
-
Topics: Given an integer array A subarray is a contiguous part of an array. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem at hand asks us to find the number of non-empty subarrays of an integer array Key Points
Approach
Plan
Let's implement this solution in PHP: 974. Subarray Sums Divisible by K <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function subarraysDivByK($nums, $k) {
$n = count($nums);
$prefixMod = 0;
$result = 0;
$modGroups = array_fill(0, $k, 0);
$modGroups[0] = 1; // Initializing for subarrays starting from the first element
foreach ($nums as $num) {
// Update the prefix sum modulo k
$prefixMod = ($prefixMod + $num % $k + $k) % $k;
// Add the number of times this prefixMod has occurred to the result
$result += $modGroups[$prefixMod];
// Update the count of this prefixMod
$modGroups[$prefixMod]++;
}
return $result;
}
// Example 1
$nums = [4, 5, 0, -2, -3, 1];
$k = 5;
echo subarraysDivByK($nums, $k); // Output: 7
// Example 2
$nums = [5];
$k = 9;
echo subarraysDivByK($nums, $k); // Output: 0
?> Explanation:
Example WalkthroughConsider the input:
Time Complexity
Output for Example
The problem can be efficiently solved using prefix sums and modulo arithmetic. By tracking the frequency of each modulo value encountered during the traversal of the array, we can determine how many subarrays have sums divisible by |
Beta Was this translation helpful? Give feedback.
The problem at hand asks us to find the number of non-empty subarrays of an integer array
nums
whose sum is divisible by a given integerk
. A subarray is defined as a contiguous part of the array. The challenge requires an efficient solution given that the length ofnums
can be as large as 3 \times 10^4.Key Points
k
.k
.Approach
Prefix Sum Modulo: The idea is to keep a running sum of ele…