![]() |
VOOZH | about |
Given an array of integers and a number k, write a function that returns true if the given array can be divided into pairs such that the sum of every pair is divisible by k.
Examples:
Input: arr[] = [9, 7, 5, 3], k = 6
Output: True
We can divide the array into (9, 3) and (7, 5). Sum of both of these pairs is a multiple of 6.Input: arr[] = [92, 75, 65, 48, 45, 35], k = 10
Output: True
We can divide the array into (92, 48), (75, 65) and (45, 35). The sum of all these pairs are multiples of 10.Input: arr[] = [91, 74, 66, 48], k = 10
Output: False
The idea is to iterate through every element arr[i]. Find if there is another not yet visited element that has a remainder like (k - arr[i]%k). If there is no such element, return false. If a pair is found, then mark both elements as visited.
True
1) If length of given array is odd, return false. An odd length array cannot be divided into pairs.
2) Traverse input array and count occurrences of all remainders (use (arr[i] % k) + k)%k for handling the case of negative integers as well).
freq[((arr[i] % k) + k) % k]++
3) Traverse input array again.
a) Find the remainder of the current element.
b) If remainder divides k into two halves, then there must be even occurrences of it as it forms pair with itself only.
c) If the remainder is 0, then there must be even occurrences.
d) Else, number of occurrences of current the remainder must be equal to a number of occurrences of "k - current remainder".
True
- In this approach we focus on the fact that if sum of two numbers mod K gives the output 0,then it is true for all instances that the individual number mod K would sum up to the K.
- We make an array of size K and there we increase the frequency and reduces it, if found a match and in the end if array has no element greater than 0 then it returns true else return false.
True