
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Smallest Common Element in All Rows in C++
Suppose we have a matrix mat where every row is sorted in non-decreasing order, we have to find the smallest common element in all rows. If there is no common element, then return -1. So if the matrix is like −
1 | 2 | 3 | 4 | 5 |
2 | 4 | 5 | 8 | 10 |
3 | 5 | 7 | 9 | 11 |
1 | 3 | 5 | 7 | 9 |
The output will be 5
To solve this, we will follow these steps −
Define a map m, n := row count of matrix,
if n is not 0, then x = column size, otherwise 0
-
for i in range 0 to n – 1
-
for j in range 0 to x – 1
if m[mat[i, j]] + 1 = i + 1, then increase m[mat[i, j]] by 1
-
-
for each key-value pair i
if value of i is n, then return the key of i
return -1
Example (C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int smallestCommonElement(vector<vector<int>>& mat) { map <int, int> m; int n = mat.size(); int x = n? mat[0].size() : 0; for(int i = 0; i < n; i++){ for(int j = 0; j < x; j++){ if(m[mat[i][j]] + 1 == i + 1){ m[mat[i][j]]++; } } } map <int, int> :: iterator it = m.begin(); while(it != m.end()){ if(it->second == n){ return it->first; } it++; } return -1; } }; main(){ vector<vector<int>> v = {{1,2,3,4,5},{2,4,5,8,10},{3,5,7,9,11},{1,3,5,7,9}}; Solution ob; cout << (ob.smallestCommonElement(v)); }
Input
[[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
Output
5
Advertisements