Give an algorithm to find a given element x (give the co-ordinates), in an n by n matrix where the rows and columns are monotonically increasing.
My thoughts:
Reduce problem set size.
In the 1st column, find the largest element <= x. We know x must be in this row or after (lower). In the last column of the matrix, find the smallest element >= x. We know x must be in this row or before. Do the same thing with the first and last rows of the matrix. We have now defined a sub-matrix such that if x is in the matrix at all, it is in this sub-matrix. Now repeat the algo on this sub-matrix… Something along these lines.
[YAAQ: Yet another arrays question.]
I think you cannot hope for more than
O(N), which is attainable. (N is the width of the matrix).Why you cannot hope for more
Imagine a matrix like this:
where
xis an unknown number (not the same number, ie. it might be a different one in every column). To satisfy the monotonicity of the matrix, you can place any of 0, 1, or 2 in all of thexplaces. So, to find if there is 1 in the matrix, you have to check all thexplaces, and there are N of them.How to make it
O(n)Imagine you have to find first column indicies with
number > q(a given number) for all rows. You start in the upper right corner of the matrix; if the number you see is greater, you go left; else go down. End when you are in the last row. The points where you went down are the places you search for. If any of them have the number you search for, you’ve found it.This algorithm is
O(n), because in each step, you either go left or down. Totally, it cannot go more thanNtimes left andNtimes down. Therefore it’sO(n).