MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / CommonMatrixElements

Class CommonMatrixElements

CommonMatrixElements.java:2–45  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import java.util.*;
2class CommonMatrixElements
3{
4 public static void main(String args[])
5 {
6 // Input
7 int mat[][] =
8 {
9 {1, 2, 1, 4, 8},
10 {8, 7, 8, 5, 1},
11 {8, 7, 7, 3, 1},
12 {8, 1, 2, 7, 9},
13 };
14 // Funtion call
15 commonElements(mat,mat.length,mat[0].length);
16 }
17 public static void commonElements(int Mat[][], int r, int c)
18 {
19 // Map
20 HashMap<Integer,Integer> map = new HashMap<>();
21
22 for(int i=0;i<c;i++)
23 {
24 map.put(Mat[0][i],1);
25 }
26
27 for(int i=1;i<r;i++)
28 {
29 for(int j=0;j<c;j++)
30 {
31 // Store and avoid duplicate elements of same row
32 if(map.containsKey(Mat[i][j]) && map.get(Mat[i][j])==i)
33 {
34 map.put(Mat[i][j],map.get(Mat[i][j])+1);
35 }
36
37 if(i==r-1 && map.containsKey(Mat[i][j]) && map.get(Mat[i][j])==r)
38 {
39 System.out.print(Mat[i][j]+" ");
40 }
41 }
42 }
43
44 }
45}
46// second approach (without data structure)
47import java.util.*;
48class Maincodes

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected