Search In An Ascending Matrix

February 10, 2012

Today’s exercise is taken from our inexhaustible list of interview questions:

Given an m by n matrix of integers with each row and column in ascending order, search the matrix and find the row and column where a key k appears, or report that k is not in the matrix. For instance, in the matrix

1 5 7 9
4 6 10 15
8 11 12 19
14 16 18 21

the key 11 appears in row 2, column 1 (indexing from 0) and the key 13 is not present in the matrix. The obvious algorithm takes time O(m × n) to search the matrix row-by-row, but you must exploit the order in the matrix to find an algorithm that takes time O(m + n).

Your task is to write the requested search function. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

“If the key k is greater than the current element then it cannot be present in the current row”

I’m sorry, I don’t understand that. Let’s look for the key 5 in the example. We start with element 1 and the condition quoted applies. So we go down. But wait, 5 can be actually found in the row in question.
Hmm…

My Attempt in Python. Basic flow is:
Scan a column top to down and stop when you hit a higher value.
Then move a column right and try finding a hit there.
Keep repeating the above 2 steps. You will eventually snake your way through the matrix.