2364. Count Number of Bad Pairs #1291
-
Topics: You are given a 0-indexed integer array Return the total number of bad pairs in 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 bad pairs in a given array. A pair (i, j) is considered bad if i < j and j - i != nums[j] - nums[i]. Directly checking each pair would be inefficient, so we use a mathematical approach to optimize the solution. Approach
Let's implement this solution in PHP: 2364. Count Number of Bad Pairs <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function countBadPairs($nums) {
$n = count($nums);
$total = $n * ($n - 1) / 2;
$freq = array();
foreach ($nums as $i => $num) {
$key = $num - $i;
if (!isset($freq[$key])) {
$freq[$key] = 0;
}
$freq[$key]++;
}
$good = 0;
foreach ($freq as $count) {
if ($count >= 2) {
$good += $count * ($count - 1) / 2;
}
}
return $total - $good;
}
// Example 1
$nums1 = [4, 1, 3, 3];
echo "Output: " . countBadPairs($nums1) . "\n"; // Output: 5
// Example 2
$nums2 = [1, 2, 3, 4, 5];
echo "Output: " . countBadPairs($nums2) . "\n"; // Output: 0
?> Explanation:
This approach efficiently reduces the problem complexity from O(n^2) to O(n) by leveraging mathematical insights and hash maps for frequency counting. |
Beta Was this translation helpful? Give feedback.
We need to count the number of bad pairs in a given array. A pair (i, j) is considered bad if i < j and j - i != nums[j] - nums[i]. Directly checking each pair would be inefficient, so we use a mathematical approach to optimize the solution.
Approach