
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 |
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
#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
- Related Questions & Answers
- Check if a pair with given product exists in Linked list in C++
- Check if subarray with given product exists in an array in Python
- Check if a File exists in C#
- Check if a given key exists in Java HashMap
- Check if a triplet with given sum exists in BST in Python
- Find the Pair with Given Sum in a Matrix using C++
- Java Program to check if a given value exists in a HashMap
- Check if a given matrix is Hankel or not in C++
- Check if a given matrix is sparse or not in C++
- Check if a file exists in Java
- Check if a list exists in given list of lists in Python
- How to check if a given key already exists in a Python dictionary?
- Check if a Matrix is Invertible in C++
- Find a pair with the given difference in C++
- How to check if an item exists in a C# array?