1497. Check If Array Pairs Are Divisible by k #650
-
Topics: Given an array of integers We want to divide the array into exactly Return Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to ensure that the array can be divided into pairs where the sum of each pair is divisible by Key Idea:For two numbers This is equivalent to: This means for each number Steps to solve:
Let's implement this solution in PHP: 1497. Check If Array Pairs Are Divisible by k <?php
/**
* @param Integer[] $arr
* @param Integer $k
* @return Boolean
*/
function canArrange($arr, $k) {
$freq = array_fill(0, $k, 0);
// Fill frequency array with counts of each remainder
foreach ($arr as $num) {
$remainder = ($num % $k + $k) % $k; // Handle negative numbers
$freq[$remainder]++;
}
// Check pairing conditions
for ($i = 1; $i < $k; $i++) {
// If remainder i has more elements than remainder k-i, it's not possible to pair them
if ($freq[$i] != $freq[$k - $i]) {
return false;
}
}
// Check for the special case of remainder 0
if ($freq[0] % 2 != 0) {
return false;
}
// If k is even, also check that elements with remainder k/2 are even
if ($k % 2 == 0 && $freq[$k / 2] % 2 != 0) {
return false;
}
return true;
}
// Example 1
$arr1 = [1, 2, 3, 4, 5, 10, 6, 7, 8, 9];
$k1 = 5;
echo canArrange($arr1, $k1) ? 'true' : 'false'; // Output: true
// Example 2
$arr2 = [1, 2, 3, 4, 5, 6];
$k2 = 7;
echo canArrange($arr2, $k2) ? 'true' : 'false'; // Output: true
// Example 3
$arr3 = [1, 2, 3, 4, 5, 6];
$k3 = 10;
echo canArrange($arr3, $k3) ? 'true' : 'false'; // Output: false
?> Explanation:
Time Complexity:
This solution efficiently checks whether it's possible to divide the array into pairs such that each pair's sum is divisible by |
Beta Was this translation helpful? Give feedback.
We need to ensure that the array can be divided into pairs where the sum of each pair is divisible by
k
. To do this efficiently, we'll use a frequency count of the remainders of elements when divided byk
.Key Idea:
For two numbers
a
andb
, their sum is divisible byk
if:(a + b) % k == 0
This is equivalent to:
(a % k + b % k) % k == 0
This means for each number
x
in the array, ifx % k = r
, we need to pair it with another numbery
such thaty % k = k - r
.Steps to solve:
k
. This will give us the needed pairing information.