Say I have a matrix (MxN
) which has its rows and columns sorted.
- All the elements in each row are arranged in increasing order
- All the elements in each column are arranged in increasing order
- All the elements are integers
No other assumptions can be made
Example:
[1 5 8 20]
[2 9 19 21]
[12 15 25 30]
I have to find if a given number is present in the matrix or not (Basic search). I have an algorithm which runs O(n)
int row = 0;
int col = N-1;
while (row < M && col >= 0) {
if (mat[row][col] == elem) {
return true;
} else if (mat[row][col] > elem) {
col--;
} else {
row++;
}
}
But I was asked an O(log (MxN)) == O(Log(n))
solution. Any ideas??