Skip to content

Instantly share code, notes, and snippets.

@dluciano
Created November 1, 2022 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dluciano/a4babd1e11475c0bdc1721f894a9df05 to your computer and use it in GitHub Desktop.
Save dluciano/a4babd1e11475c0bdc1721f894a9df05 to your computer and use it in GitHub Desktop.
1198. Find Smallest Common Element in All Rows
public class Solution {
public int SmallestCommonElement(int[][] mat) {
var cursors = new int[mat.Length];
var ROWS = mat.Length;
var COLS = mat[0].Length;
while(true){
var row = 0;
var allFound = true;
var min = -1;
while(row + 1 < ROWS){
while(mat[row + 1][cursors[row + 1]] < mat[row][cursors[row]]){
if(cursors[row + 1] + 1 >= COLS)
return -1;
cursors[row + 1]++;
}
min = mat[row][cursors[row]];
if(mat[row][cursors[row]] == mat[row + 1][cursors[row + 1]]){
row++;
continue;
}
allFound = false;
break;
}
if(allFound)
return min;
while(row >= 0){
cursors[row]++;
if(cursors[row] == COLS)
return -1;
row--;
}
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment