![]() |
VOOZH | about |
Given an array with distinct elements, the task is to find the pairs in the array such that a % b = k, where k is a given integer. You may assume that a and b are in small range
Examples :
Input : arr[] = {2, 3, 5, 4, 7}
k = 3
Output : (7, 4), (3, 4), (3, 5), (3, 7)
7 % 4 = 3
3 % 4 = 3
3 % 5 = 3
3 % 7 = 3Input: arr[] = [1, 2], k = 3
Output: 0
Explanation: No pairs give remainder 3.
We consider all pairs one by one and check their modulo is equal to k or not. If equals to k, then print that pair.
(3, 5) (3, 4) (3, 7) (7, 4)
The idea is based on below observations :
If arr[i] % arr[j] = k,
==> arr[i] = x * arr[j] + k
==> (arr[i] - k) = x * arr[j]
We find all divisors of (arr[i] - k)
and see if they are present in arr[].
To quickly check if an element is present in the array, we use hashing.
(2, 3) (2, 5) (5, 3) (2, 4)