
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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 triplet with given sum exists in BST in Python
- Check if a File exists in C#
- Find the Pair with Given Sum in a Matrix using C++
- Check if a given key exists in Java HashMap
- Check if a given matrix is sparse or not in C++
- Check if a given matrix is Hankel or not in C++
- Java Program to check if a given value exists in a HashMap
- 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++
- How to check if an item exists in a C# array?
- How to Check if a Key Exists in the Hashtable in C#?
- Check if a file exists in Java\n
