Input: arr =[1,2,3,4,5,10,6,7,8,9], k =5Output: trueExplanation: Pairs are(1,9),(2,8),(3,7),(4,6) and (5,10).
Example 2:
1
2
3
Input: arr =[1,2,3,4,5,6], k =7Output: trueExplanation: Pairs are(1,6),(2,5) and(3,4).
Example 3:
1
2
3
Input: arr =[1,2,3,4,5,6], k =10Output: falseExplanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.
Create Frequency Array: Initialize an array freq of size k to zero.
Fill Frequency Array: For each element in the array, calculate its remainder rem when divided by k. If rem is negative, add k to it to ensure it is positive. Increment the corresponding index in the freq array.
Validate Remainder Frequencies:
For each i from 1 to k-1, check if freq[i] equals freq[k - i].
Check if freq[0] is even.
Return Result: If all conditions are satisfied, return true; otherwise, return false.
publicclassSolution {
publicbooleancanArrange(int[] arr, int k) {
// Create a frequency array to count occurrences // of all remainders when divided by kint[] freq =newint[k];
// Fill remainder frequency arrayfor (int num : arr) {
int rem = num % k;
if (rem < 0) {
rem += k;
}
freq[rem]++;
}
// Check if frequency of remainders satisfies the pair conditionfor (int i = 1; i < k; i++) {
if (freq[i]!= freq[k - i]) {
returnfalse;
}
}
// Special check for remainder 0 elements, count of such elements must// be evenreturn freq[0]% 2 == 0;
}
}
classSolution:
defcanArrange(self, arr: List[int], k: int) -> bool:
# If the array length is odd, we cannot divide it into pairsif len(arr) %2!=0:
returnFalse# Create a frequency array to count occurrences of all remainders when divided by k freq = [0] * k
# Fill remainder frequency arrayfor num in arr:
rem = num % k
if rem <0:
rem += k
freq[rem] +=1# Check if frequency of remainders satisfies the pair conditionfor i in range(1, k):
if freq[i] != freq[k - i]:
returnFalse# Special check for remainder 0 elements, count of such elements must be evenreturn freq[0] %2==0
⏰ Time complexity: O(n + k), where n is the length of the array. We make a single pass through the array to populate the frequency array which takes O(n) and another pass to check the remainder conditions which takes O(k).
🧺 Space complexity: O(k) for storing the remainder frequencies in an array of size k.