I have a x by y matrix, where each row and each column are in ascending order as given below.
1 5 7 9
4 6 10 15
8 11 12 19
14 16 18 21
How to search this matrix for a number in O(x+y)?
I was asked this question for an interview, but could not figure out the way. Curious to know if it could be done.
Start at the last element of the first row(top-right corner).
Compare it with the
key. We have 3 cases:If they are equal we are done.
If
keyis greater than that elementthen it means
keycannot be presentin that row so move the search
to the element below it.
If
keyis less than that element thenit means
keycould be present in thatrow towards left and cannot be present in the column further down, so move the search
to the element left of it.
Keep doing it till you find the element or you cannot further move(key does not exist).
Pseudo code: