Find set of m-elements with difference of any two elements is divisible by k in C++


Suppose we have an array with N positive integers, and another variable K. We have to find the exactly m-elements, such that difference between any two elements is equal to k. So if the array is A = [4, 7, 10, 6, 9], and k = 3 and m = 3, then output will be “yes”. As we can find three elements like 4, 7, 10.

To solve this, we have to keep track of the remainders, when an element is divided by k. Now create a multi-dimensional array rem[][] of size k, its index is showing the remainder, and elements will be the elements as per their corresponding remainders when divided by k. Now by traversing the remainder set, we can get a set whose size is greater than or equal to the required size m if exists. And the difference of any elements of that set will be divisible by k.

Example

 Live Demo

#include<iostream>
#include<vector>
using namespace std;
void searchElementsSet(int arr[], int n, int k, int m) {
   vector<int> rem_matrix[k];
   for (int i = 0; i < n; i++) {
      int rem = arr[i] % k;
      rem_matrix[rem].push_back(arr[i]);
   }
   for (int i = 0; i < k; i++) {
      if (rem_matrix[i].size() >= m) {
         cout << "Yes Possible"<<endl;
         for (int j = 0; j < m; j++)
            cout << rem_matrix[i][j] << " ";
         return;
      }
   }
   cout << "Impossible";
}
int main() {
   int arr[] = {4, 7, 10, 6, 9};
   int k = 3;
   int m = 3;
   int n = sizeof(arr) / sizeof(arr[0]);
   searchElementsSet(arr, n, k, m);
}

Output

Yes Possible
4 7 10

Updated on: 18-Dec-2019

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements