VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-pairs-b-array-b-k/

⇱ Find all pairs (a, b) in an array such that a % b = k - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find all pairs (a, b) in an array such that a % b = k

Last Updated : 24 Oct, 2024

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 = 3

Input: arr[] = [1, 2], k = 3
Output: 0
Explanation: No pairs give remainder 3.

Naive Approach - O(n^2) Time and O(1) Space

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.  


Output
(3, 5) (3, 4) (3, 7) (7, 4) 

Efficient Solution for Small Values and Large Arrays - O(n* sqrt(max))) Time and O(n) Space

The idea is based on below observations : 

  1. If k itself is present in arr[], then k forms a pair with all elements arr[i] where k < arr[i]. For all such arr[i], we have k % arr[i] = k.
  2. For all elements greater than or equal to k, we use the following fact.

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. 


Output
(2, 3) (2, 5) (5, 3) (2, 4) 


Comment
Article Tags: