2176. Count Equal and Divisible Pairs in an Array #1570
-
Topics: Given a 0-indexed integer 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 pairs (i, j) in a given array such that the elements at these indices are equal and the product of their indices is divisible by a given integer k. ApproachThe approach involves iterating through all possible pairs of indices (i, j) where i < j. For each pair, we check two conditions:
Given the constraints that the array length is at most 100, a brute-force approach is feasible. This approach involves checking each pair directly, which is manageable due to the small size of the input. Let's implement this solution in PHP: 2176. Count Equal and Divisible Pairs in an Array <?php
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function countPairs($nums, $k) {
$count = 0;
$n = count($nums);
for ($i = 0; $i < $n - 1; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
if ($nums[$i] == $nums[$j] && ($i * $j) % $k == 0) {
$count++;
}
}
}
return $count;
}
// Example 1:
$nums1 = array(3, 1, 2, 2, 2, 1, 3);
$k1 = 2;
echo "Output: " . countPairs($nums1, $k1) . "\n"; // Output: 4
// Example 2:
$nums2 = array(1, 2, 3, 4);
$k2 = 1;
echo "Output: " . countPairs($nums2, $k2) . "\n"; // Output: 0
?> Explanation:
This approach ensures that we check all possible pairs efficiently within the constraints, providing the correct result with a time complexity of O(n^2), which is acceptable given the input size. |
Beta Was this translation helpful? Give feedback.
We need to count the number of pairs (i, j) in a given array such that the elements at these indices are equal and the product of their indices is divisible by a given integer k.
Approach
The approach involves iterating through all possible pairs of indices (i, j) where i < j. For each pair, we check two conditions:
Given the constraints that the array length is at most 100, a brute-force approach is feasible. This approach involves checking each pair directly, which is manageable due to the small size of the input.
Let's implement this solution in PHP: 2176. Count Equal and Divisible Pairs in an Array
<…