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

Class Maincodes

CommonMatrixElements.java:48–113  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

46// second approach (without data structure)
47import java.util.*;
48class Maincodes
49{
50 public static void main(String args[])
51 {
52 // Input
53 int mat[][] =
54 {
55 {1, 2, 1, 4, 8},
56 {8, 7, 8, 5, 1},
57 {8, 7, 7, 3, 1},
58 {8, 1, 1, 7, 9},
59 };
60 // Funtion call
61 commonElements(mat,mat.length,mat[0].length);
62 }
63 // function to check if there is any duplicate elements in the firstRow
64 public static boolean seen(int arr[],int element,int end)
65 {
66 for(int i=0;i<end;i++)
67 {
68 if(element==arr[i]) return true;
69 }
70 return false;
71 }
72 public static void commonElements(int Mat[][], int r, int c)
73 {
74 // pick one by one element of the first row and check if they are present in all rows.
75 for(int firstRow=0;firstRow<c;firstRow++)
76 {
77 // pick element
78 int element=Mat[0][firstRow];
79 // if duplicate then skip the element
80 if(seen(Mat[0],element,firstRow)) continue;
81 // variable for tracking rows.
82 int count=0;
83 // if element is not present in anyone of the row then skip the element.
84 int flag=0;
85 // traverse from 1st to last row
86 for(int row=1;row<r;row++)
87 {
88 for(int col=0;col<c;col++)
89 {
90 // if element is found then increment the counter
91 if(element==Mat[row][col])
92 {
93 count++;
94 // if present in last row and count is equal to row-1, then print it
95 if(row==r-1 && count==r-1)
96 System.out.println(element);
97 // if count is same as row then break to avoid adding duplicates
98 else if(row!=r-1 && count==row)
99 break;
100 // if element not present in the current row then set flag to 1,
101 else
102 {
103 flag=1;
104 break;
105 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected