Q-3 PepCoding | Check If An Array Can Be Divided Into Pairs Whose Sum Is Divisible By K
Mon Jan 23 2023 06:50:14 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
class Solution {
public boolean canArrange(int[] arr, int k) {
//HashMap and heap Q-3
int frequency[] = new int[k];
//find remainders
for(int val : arr){
int rem = val%k;
//if -ve add k to it
if(rem < 0) rem +=k;
frequency[rem]++;
}
//check all rem and [k-rem]
if(frequency[0] %2 != 0) return false;
for(int i = 1 ; i <= k/2 ; i++){
if(frequency[i] != frequency[k-i])
return false;
}
return true;
}
}
content_copyCOPY
https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/hashmap-and-heaps/check-if-an-array-cab-be-divided-into-pairs-whose-sum-is-divisible-by-k-official/ojquestion
Comments