1198. Find Smallest Common Element in All Rows
Last updated
Last updated
/**
* Time complexity : O(MNlogN). We iterate through m elements in the first row.
* For each element, we perform the binary search n times over m elements.
* Space complexity : O(1)
*/
class Solution {
public int smallestCommonElement(int[][] mat) {
if(mat == null || mat.length == 0 || mat[0].length == 0) {
return -1;
}
int row = mat.length, col = mat[0].length;
int count = 0, min = Integer.MAX_VALUE;
for(int j = 0; j < col; j++) {
count = 1;
for(int i = 1; i < row; i++) {
if(binarySearch(mat[i], mat[0][j]) == -1) {
break;
} else {
count++;
}
}
if(count == row && mat[0][j] < min) {
min = mat[0][j];
}
}
return min == Integer.MAX_VALUE? -1: min;
}
private int binarySearch(int[] arr, int target) {
int low = 0, high = arr.length-1;
while(low <= high) {
int mid = (low + high) / 2;
if(arr[mid] == target) {
return mid;
}
if(target > arr[mid]) {
low = mid + 1;
} else {
high = mid-1;
}
}
return -1;
}
}/**
* Time complexity : O(MN). we iterate through all MN elements in the matrix
* in the worst case.
* Space complexity : O(M), M is the row size. To store row indices.
*/
class Solution {
public int smallestCommonElement(int[][] mat) {
if(mat == null || mat.length == 0 || mat[0].length == 0) {
return -1;
}
int row = mat.length, col = mat[0].length;
int count = 0, min = 0;
int[] pos = new int[row];
while(true) {
for(int i = 0; i < row; i++) {
while(pos[i] < col && mat[i][pos[i]] < min) {
pos[i]++;
}
if(pos[i] >= col) {
return -1;
}
count++;
if(mat[i][pos[i]] != min) {
count = 1;
min = mat[i][pos[i]];
} else if(count == row) {
return min;
}
}
}
}
}