Find distinct elements common to all rows of a matrix
Last Updated :
15 Apr, 2023
Given a n x n matrix. The problem is to find all the distinct elements common to all rows of the matrix. The elements can be printed in any order.
Examples:
Input : mat[][] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} }
Output : 2 3
Input : mat[][] = { {12, 1, 14, 3, 16},
{14, 2, 1, 3, 35},
{14, 1, 14, 3, 11},
{14, 25, 3, 2, 1},
{1, 18, 3, 21, 14} }
Output : 1 3 14
Method 1: Using three nested loops. Check if an element of 1st row is present in all the subsequent rows. Time Complexity of O(n3). Extra space could be required to handle the duplicate elements.
Method 2: Sort all the rows of the matrix individually in increasing order. Then apply a modified approach to the problem of finding common elements in 3 sorted arrays. Below an implementation for the same is given.
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
void sortRows( int mat[][MAX], int n)
{
for ( int i=0; i<n; i++)
sort(mat[i], mat[i] + n);
}
void findAndPrintCommonElements( int mat[][MAX], int n)
{
sortRows(mat, n);
int curr_index[n];
memset (curr_index, 0, sizeof (curr_index));
int f = 0;
for (; curr_index[0]<n; curr_index[0]++)
{
int value = mat[0][curr_index[0]];
bool present = true ;
for ( int i=1; i<n; i++)
{
while (curr_index[i] < n &&
mat[i][curr_index[i]] <= value)
curr_index[i]++;
if (mat[i][curr_index[i]-1] != value)
present = false ;
if (curr_index[i] == n)
{
f = 1;
break ;
}
}
if (present)
cout << value << " " ;
if (f == 1)
break ;
}
}
int main()
{
int mat[][MAX] = { {12, 1, 14, 3, 16},
{14, 2, 1, 3, 35},
{14, 1, 14, 3, 11},
{14, 25, 3, 2, 1},
{1, 18, 3, 21, 14}
};
int n = 5;
findAndPrintCommonElements(mat, n);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static void sortRows( int mat[][], int n)
{
for ( int i= 0 ; i<n; i++)
Arrays.sort(mat[i]);
}
public static void findAndPrintCommonElements( int mat[][],
int n)
{
sortRows(mat, n);
int curr_index[] = new int [n];
int f = 0 ;
for (; curr_index[ 0 ]<n; curr_index[ 0 ]++)
{
int value = mat[ 0 ][curr_index[ 0 ]];
boolean present = true ;
for ( int i= 1 ; i<n; i++)
{
while (curr_index[i] < n &&
mat[i][curr_index[i]] <= value)
curr_index[i]++;
if (mat[i][curr_index[i]- 1 ] != value)
present = false ;
if (curr_index[i] == n)
{
f = 1 ;
break ;
}
}
if (present)
System.out.print(value+ " " );
if (f == 1 )
break ;
}
}
public static void main(String[] args)
{
int mat[][] = { { 12 , 1 , 14 , 3 , 16 },
{ 14 , 2 , 1 , 3 , 35 },
{ 14 , 1 , 14 , 3 , 11 },
{ 14 , 25 , 3 , 2 , 1 },
{ 1 , 18 , 3 , 21 , 14 }
};
int n = 5 ;
findAndPrintCommonElements(mat, n);
}
}
|
Python3
MAX = 100
def sortRows(mat, n):
for i in range ( 0 , n):
mat[i].sort();
def findAndPrintCommonElements(mat, n):
sortRows(mat, n)
curr_index = [ 0 ] * n
for i in range ( 0 , n):
curr_index[i] = 0
f = 0
while (curr_index[ 0 ] < n):
value = mat[ 0 ][curr_index[ 0 ]]
present = True
for i in range ( 1 , n):
while (curr_index[i] < n and
mat[i][curr_index[i]] < = value):
curr_index[i] = curr_index[i] + 1
if (mat[i][curr_index[i] - 1 ] ! = value):
present = False
if (curr_index[i] = = n):
f = 1
break
if (present):
print (value, end = " " )
if (f = = 1 ):
break
curr_index[ 0 ] = curr_index[ 0 ] + 1
mat = [[ 12 , 1 , 14 , 3 , 16 ],
[ 14 , 2 , 1 , 3 , 35 ],
[ 14 , 1 , 14 , 3 , 11 ],
[ 14 , 25 , 3 , 2 , 1 ],
[ 1 , 18 , 3 , 21 , 14 ]]
n = 5
findAndPrintCommonElements(mat, n)
|
C#
using System;
class GFG
{
public static void sortRows( int [][] mat, int n)
{
for ( int i = 0; i < n; i++)
{
Array.Sort(mat[i]);
}
}
public static void findAndPrintCommonElements( int [][] mat,
int n)
{
sortRows(mat, n);
int [] curr_index = new int [n];
int f = 0;
for (; curr_index[0] < n; curr_index[0]++)
{
int value = mat[0][curr_index[0]];
bool present = true ;
for ( int i = 1; i < n; i++)
{
while (curr_index[i] < n &&
mat[i][curr_index[i]] <= value)
{
curr_index[i]++;
}
if (mat[i][curr_index[i] - 1] != value)
{
present = false ;
}
if (curr_index[i] == n)
{
f = 1;
break ;
}
}
if (present)
{
Console.Write(value + " " );
}
if (f == 1)
{
break ;
}
}
}
public static void Main( string [] args)
{
int [][] mat = new int [][]
{
new int [] {12, 1, 14, 3, 16},
new int [] {14, 2, 1, 3, 35},
new int [] {14, 1, 14, 3, 11},
new int [] {14, 25, 3, 2, 1},
new int [] {1, 18, 3, 21, 14}
};
int n = 5;
findAndPrintCommonElements(mat, n);
}
}
|
Javascript
<script>
function sortRows(mat,n)
{
for (let i=0; i<n; i++)
mat[i].sort( function (a,b){ return a-b;});
}
function findAndPrintCommonElements(mat,n)
{
sortRows(mat, n);
let curr_index = new Array(n);
for (let i=0;i<n;i++)
{
curr_index[i]=0;
}
let f = 0;
for (; curr_index[0]<n; curr_index[0]++)
{
let value = mat[0][curr_index[0]];
let present = true ;
for (let i=1; i<n; i++)
{
while (curr_index[i] < n &&
mat[i][curr_index[i]] <= value)
curr_index[i]++;
if (mat[i][curr_index[i]-1] != value)
present = false ;
if (curr_index[i] == n)
{
f = 1;
break ;
}
}
if (present)
document.write(value+ " " );
if (f == 1)
break ;
}
}
let mat = [[12, 1, 14, 3, 16],
[14, 2, 1, 3, 35],
[14, 1, 14, 3, 11],
[14, 25, 3, 2, 1],
[1, 18, 3, 21, 14]]
let n = 5;
findAndPrintCommonElements(mat, n);
</script>
|
Time Complexity: O(n2log n), each row of size n requires O(nlogn) for sorting and there are total n rows.
Auxiliary Space: O(n) to store current column indexes for each row.
Method 3: It uses the concept of hashing. The following steps are:
- Map the element of the 1st row in a hash table. Let it be hash.
- Fow row = 2 to n
- Map each element of the current row into a temporary hash table. Let it be temp.
- Iterate through the elements of hash and check that the elements in hash are present in temp. If not present then delete those elements from hash.
- When all the rows are being processed in this manner, then the elements left in hash are the required common elements.
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
void findAndPrintCommonElements( int mat[][MAX], int n){
unordered_set< int > us;
for ( int i=0; i<n; i++)
us.insert(mat[0][i]);
for ( int i=1; i<n; i++){
unordered_set< int > temp;
unordered_set< int > common;
for ( int j=0; j<n; j++)
temp.insert(mat[i][j]);
for ( auto itr : us)
if (temp.find(itr) != temp.end()) common.insert(itr);
us = common;
if (us.size() == 0)
break ;
}
for ( auto itr : us)
cout << itr << " " ;
}
int main(){
int mat[][MAX] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} };
int n = 4;
findAndPrintCommonElements(mat, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int MAX = 100 ;
@SuppressWarnings ( "unchecked" )
static void findAndPrintCommonElements( int mat[][], int n)
{
HashSet<Integer> us = new HashSet<Integer>();
for ( int i = 0 ; i < n; i++)
us.add(mat[ 0 ][i]);
for ( int i = 1 ; i < n; i++)
{
HashSet<Integer> temp = new HashSet<Integer>();
for ( int j = 0 ; j < n; j++)
temp.add(mat[i][j]);
HashSet<Integer> itr=(HashSet<Integer>) us.clone();
for ( int x :itr)
if (!temp.contains(x))
us.remove(x);
if (us.size() == 0 )
break ;
}
HashSet<Integer> itr1=(HashSet<Integer>) us.clone();
for ( int x :itr1)
System.out.print(x+ " " );
}
public static void main(String[] args)
{
int mat[][] = { { 2 , 1 , 4 , 3 },
{ 1 , 2 , 3 , 2 },
{ 3 , 6 , 2 , 3 },
{ 5 , 2 , 5 , 3 } };
int n = 4 ;
findAndPrintCommonElements(mat, n);
}
}
|
Python3
MAX = 100
def findAndPrintCommonElements(mat, n):
us = dict ()
for i in range (n):
us[(mat[ 0 ][i])] = 1
for i in range ( 1 , n):
temp = dict ()
for j in range (n):
temp[(mat[i][j])] = 1
for itr in list (us):
if itr not in temp:
del us[itr]
if ( len (us) = = 0 ):
break
for itr in list (us)[:: - 1 ]:
print (itr, end = " " )
mat = [[ 2 , 1 , 4 , 3 ],
[ 1 , 2 , 3 , 2 ],
[ 3 , 6 , 2 , 3 ],
[ 5 , 2 , 5 , 3 ]]
n = 4
findAndPrintCommonElements(mat, n)
|
C#
using System;
using System.Collections.Generic;
public class GFG{
static int MAX = 100;
static void findAndPrintCommonElements( int [,]mat, int n)
{
HashSet< int > us = new HashSet< int >();
for ( int i = 0; i < n; i++)
us.Add(mat[0, i]);
for ( int i = 1; i < n; i++)
{
HashSet< int > temp = new HashSet< int >();
for ( int j = 0; j < n; j++)
temp.Add(mat[i,j]);
HashSet< int > itr= new HashSet< int >(us);
foreach ( int x in itr)
if (!temp.Contains(x))
us.Remove(x);
if (us.Count == 0)
break ;
}
HashSet< int > itr1= new HashSet< int >(us);
foreach ( int x in itr1)
Console.Write(x+ " " );
}
public static void Main(String[] args)
{
int [,]mat = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} };
int n = 4;
findAndPrintCommonElements(mat, n);
}
}
|
Javascript
var MAX = 100;
function findAndPrintCommonElements(mat, n)
{
var us = new Set();
for ( var i = 0; i < n; i++)
us.add(mat[0][i]);
for ( var i = 1; i < n; i++)
{
var temp = new Set();
for ( var j = 0; j < n; j++)
temp.add(mat[i][j]);
for ( var itr of us)
{
if (!temp.has(itr))
us. delete (itr);
}
if (us.size == 0)
break ;
}
for ( var itr of [...us].sort((a,b)=>b-a))
document.write( itr + " " );
}
var mat = [ [2, 1, 4, 3],
[1, 2, 3, 2],
[3, 6, 2, 3],
[5, 2, 5, 3]];
var n = 4;
findAndPrintCommonElements(mat, n);
|
Output:
3 2
Time Complexity: O(n2)
Space Complexity: O(n), since n extra space has been taken.
Method 4: Using Map
- Insert all the elements of the 1st row in the map.
- Now we check that the elements present in the map are present in each row or not.
- If the element is present in the map and is not duplicated in the current row, then we increment the count of the element in the map by 1.
- If we reach the last row while traversing and if the element appears (N-1) times before then we print the element.
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
void distinct( int mat[][MAX], int N)
{
unordered_map< int , int > ans;
for ( int j = 0; j < N; j++) {
ans[(mat[0][j])]=1;
}
for ( int i = 1; i < N; i++) {
for ( int j = 0; j < N; j++) {
if (ans[(mat[i][j])] != 0
&& ans[(mat[i][j])] == i) {
ans[(mat[i][j])]= i + 1;
if (i == N - 1) {
cout<<mat[i][j]<< " " ;
}
}
}
}
}
int main()
{
int N=4;
int mat[][MAX] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} };
distinct(mat, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static void distinct( int matrix[][], int N)
{
Map<Integer, Integer> ans = new HashMap<>();
for ( int j = 0 ; j < N; j++) {
ans.put(matrix[ 0 ][j], 1 );
}
for ( int i = 1 ; i < N; i++) {
for ( int j = 0 ; j < N; j++) {
if (ans.get(matrix[i][j]) != null
&& ans.get(matrix[i][j]) == i) {
ans.put(matrix[i][j], i + 1 );
if (i == N - 1 ) {
System.out.print(matrix[i][j]
+ " " );
}
}
}
}
}
public static void main(String[] args)
{
int matrix[][] = { { 2 , 1 , 4 , 3 },
{ 1 , 2 , 3 , 2 },
{ 3 , 6 , 2 , 3 },
{ 5 , 2 , 5 , 3 } };
int n = 4 ;
distinct(matrix, n);
}
}
|
Python3
def distinct(matrix, N):
ans = {}
for j in range (N):
ans[(matrix[ 0 ][j])] = 0
for i in range (N):
for j in range (N):
if matrix[i][j] in ans and ans[(matrix[i][j])] = = i:
ans[(matrix[i][j])] = i + 1
if (i = = N - 1 ):
print (matrix[i][j],end = " " )
matrix = [ [ 2 , 1 , 4 , 3 ],
[ 1 , 2 , 3 , 2 ],
[ 3 , 6 , 2 , 3 ],
[ 5 , 2 , 5 , 3 ] ]
n = 4
distinct(matrix, n)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void distinct( int [,] matrix, int N)
{
Dictionary< int ,
int > ans = new Dictionary< int ,
int >();
for ( int j = 0; j < N; j++)
{
ans[(matrix[0, j])] = 1;
}
for ( int i = 1; i < N; i++)
{
for ( int j = 0; j < N; j++)
{
if (ans.ContainsKey(matrix[i, j]) &&
ans[(matrix[i, j])] == i)
{
ans[(matrix[i, j])] = i + 1;
if (i == N - 1)
{
Console.Write(matrix[i, j] + " " );
}
}
}
}
}
public static void Main( string [] args)
{
int [,] matrix = { { 2, 1, 4, 3 },
{ 1, 2, 3, 2 },
{ 3, 6, 2, 3 },
{ 5, 2, 5, 3 } };
int n = 4;
distinct(matrix, n);
}
}
|
Javascript
<script>
function distinct(matrix, N)
{
var ans = new Map()
for ( var j = 0; j < N; j++)
{
ans.set(matrix[0][j], 1);
}
for ( var i = 1; i < N; i++)
{
for ( var j = 0; j < N; j++)
{
if (ans.has(matrix[i][j]) &&
ans.get(matrix[i][j]) == i)
{
ans.set(matrix[i][j], i + 1);
if (i == N - 1)
{
document.write(matrix[i][j] + " " );
}
}
}
}
}
var matrix = [ [ 2, 1, 4, 3 ],
[ 1, 2, 3, 2 ],
[ 3, 6, 2, 3 ],
[ 5, 2, 5, 3 ] ];
var n = 4;
distinct(matrix, n);
</script>
|
Time Complexity: O(n2)
Space Complexity: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...