Friday, 17 June 2016

Zoho interview question


Problem statement:
Given an m x n matrix, find all common elements present
in all rows in O(mn) time and one traversal of matrix.

Example:
Input:
mat[4][5] = {{1, 2, 1, 4, 8},
             {3, 7, 8, 5, 1},
             {8, 7, 7, 3, 1},
             {8, 1, 2, 7, 9}};

Output:
1 8 or 8 1
8 and 1 are present in all rows

solution:

#include<stdio.h>
int main(){
int arr[5][5];
int c=0,row=5,col=5,i=0,j=0,k=1,l=0;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
scanf("%d",&arr[i][j]);
for(j=0;j<col;j++){
 for(k=1;k<row;k++){
  for(l=0;l<col;l++){
   if(arr[0][j]==arr[k][l]){
    c++;  
    arr[k][l]=0;
    break;
   }
  }
 }
 if(c==row-1)
  printf("%d ",arr[0][j]);
 c=0;
}
return 0;
}

No comments:

Post a Comment