2799. Count Complete Subarrays in an Array #1601
-
Topics: You are given an array We call a subarray of an array complete if the following condition is satisfied:
Return the number of complete subarrays. A subarray is a contiguous non-empty part of 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 complete subarrays in a given array. A complete subarray is defined as a contiguous subarray that contains exactly the same number of distinct elements as the entire array. Approach
Let's implement this solution in PHP: 2799. Count Complete Subarrays in an Array <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function countCompleteSubarrays($nums) {
$unique = array_unique($nums);
$k = count($unique);
if ($k == 0) {
return 0;
}
return atMost($nums, $k) - atMost($nums, $k - 1);
}
/**
* @param $nums
* @param $m
* @return int
*/
function atMost($nums, $m) {
$count = array();
$left = 0;
$res = 0;
$distinct = 0;
$n = count($nums);
for ($right = 0; $right < $n; $right++) {
$num = $nums[$right];
if (!isset($count[$num]) || $count[$num] == 0) {
$distinct++;
$count[$num] = 0;
}
$count[$num]++;
while ($distinct > $m) {
$leftNum = $nums[$left];
$count[$leftNum]--;
if ($count[$leftNum] == 0) {
$distinct--;
}
$left++;
}
$res += $right - $left + 1;
}
return $res;
}
// Test Example 1
$nums1 = array(1, 3, 1, 2, 2);
echo "Output 1: " . countCompleteSubarrays($nums1) . "\n"; // Expected: 4
// Test Example 2
$nums2 = array(5, 5, 5, 5);
echo "Output 2: " . countCompleteSubarrays($nums2) . "\n"; // Expected: 10
?> Explanation:
This approach efficiently narrows down the problem using the sliding window technique, ensuring we count the required subarrays in linear time relative to the input size, making it suitable for large arrays up to the constraint limits. |
Beta Was this translation helpful? Give feedback.
We need to count the number of complete subarrays in a given array. A complete subarray is defined as a contiguous subarray that contains exactly the same number of distinct elements as the entire array.
Approach
k
.k
distinct elements. This is done by leveraging two helper functions:m
distinct elements.k
distinct elements can be derived by subtrac…