Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number in sorted matrix (Rows n Columns) in O(log n) [duplicate]

Say I have a matrix (MxN) which has its rows and columns sorted.

  1. All the elements in each row are arranged in increasing order
  2. All the elements in each column are arranged in increasing order
  3. All the elements are integers
  4. 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??

like image 704
noMAD Avatar asked May 14 '12 19:05

noMAD


1 Answers

O(log (M * N)) solution is not possible for this task.

Let's look at a simplified task: in "sorted" square matrix assume all elements above secondary diagonal (green) less than given number, all elements below secondary diagonal (red) greater than given number, and no additional assumptions for elements on secondary diagonal (yellow).

enter image description here

Neither original assumptions of this task, nor these additional assumptions tell us how elements on secondary diagonal are related to each other. Which means we just have an unsorted array of N integers. We cannot find given number in the unsorted array faster than O(N). So for original (more complicated) problem with square matrix we cannot get a solution better than O(N).

For a rectangular matrix, stretch the square picture and set the additional assumptions accordingly. Here we have min(N,M) sorted sub-arrays of size max(N,M)/min(N,M) each. The best way to search here is to use linear search to find one or several sub-arrays that may contain given value, then to use binary search inside these sub-arrays. In the worst case it is necessary to binary-search in each sub-array. Complexity is O(min(N,M) * (1 + log(max(N,M) / min(N,M)))). So for original (more complicated) problem with rectangular matrix we cannot get a solution better than O(min(N,M) * ( 1 + log(max(N,M)) - log(min(N,M)))).

like image 129
Evgeny Kluev Avatar answered Oct 04 '22 08:10

Evgeny Kluev