Check if a pair with given product exists in a Matrix in C++


We have one matrix of order N x M. And a product K. The task is to check whether a pair with the given product is present in the matrix or not.

Suppose a matrix is like below −

1234
5678
9101112
13141516

Now if the K is 42, then there is a pair like (6, 7)

To solve this problem, we will use hashing. We will create hash table by taking all elements of the matrix. We will start traversing the matrix, while traversing, check whether the current element of the matrix is divisible by the given product, and when the product K is divided by current element, the dividend will also present in the hash table. So the required condition is like −

(k mod matrix[i, n]) is false, and hash table has k/matrix[i, j]

If present, then return true, otherwise insert current element into hash table.

If no pairs have found, return false.

Example

 Live Demo

#include <iostream>
#include <unordered_set>
#define N 4
#define M 4
using namespace std;
bool isPairPresent(int matrix[N][M], int K) {
   unordered_set<int> s;
   for (int i = 0; i < N; i++) {
      for (int j = 0; j < M; j++) {
         if ((K % matrix[i][j] == 0) && (s.find(K / matrix[i][j]) != s.end())) {
            return true;
         } else {
            s.insert(matrix[i][j]);
         }
      }
   }
   return false;
}
int main() {
   int matrix[N][M] = {{1, 2, 3, 4},
      {5, 6, 7, 8},
      {9, 10, 11, 12},
      {13, 14, 15, 16}};
      int k = 42;
   if (isPairPresent(matrix, k) == false)
      cout << "NO PAIR EXIST";
   else
      cout << "Pair is present";
}

Output

Pair is present

Updated on: 22-Oct-2019

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements