2845. Count of Interesting Subarrays #1605
-
Topics: You are given a 0-indexed integer array Your task is to find the count of subarrays that are interesting. A subarray
Return an integer denoting the count of interesting subarrays. Note: A subarray is a contiguous non-empty sequence of elements within an array. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of interesting subarrays in a given array Approach
Let's implement this solution in PHP: 2845. Count of Interesting Subarrays <?php
/**
* @param Integer[] $nums
* @param Integer $modulo
* @param Integer $k
* @return Integer
*/
function countInterestingSubarrays($nums, $modulo, $k) {
$map = array();
$map[0] = 1;
$current_count = 0;
$result = 0;
foreach ($nums as $num) {
if ($num % $modulo == $k) {
$current_count++;
}
$target = (($current_count - $k) % $modulo + $modulo) % $modulo;
if (isset($map[$target])) {
$result += $map[$target];
}
$current_mod = $current_count % $modulo;
if (isset($map[$current_mod])) {
$map[$current_mod]++;
} else {
$map[$current_mod] = 1;
}
}
return $result;
}
// Example usage:
$nums1 = array(3, 2, 4);
$modulo1 = 2;
$k1 = 1;
echo countInterestingSubarrays($nums1, $modulo1, $k1) . "\n"; // Output: 3
$nums2 = array(3, 1, 9, 6);
$modulo2 = 3;
$k2 = 0;
echo countInterestingSubarrays($nums2, $modulo2, $k2) . "\n"; // Output: 2
?> Explanation:
This approach efficiently counts the interesting subarrays in linear time, making it suitable for large input sizes as specified in the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to count the number of interesting subarrays in a given array
nums
based on specific conditions. A subarray is considered interesting if the count of elements in it that satisfy a certain modulo condition, when taken modulomodulo
, equalsk
.Approach
modulo
. This allows us to efficiently check how many times a specific value has been encountered, which helps in determining the number of interesting subarrays ending a…