I recently sat in an interview and I was asked this question:
Given a 2d array of integers, where:
Every row is sorted from left to right.
Every column is sorted from top to bottom.
What is the best algorithm for finding the position of an element x?
I was happy, as I had done this before, and this was my answer:
Start at the top right position.
If e at that position is greater than x,then definitely, all elements of that column are greater than x and we move one column back.
If e at that position is less than x, then definitely all the elements behind e are less than x and all elements after e are greater than x and so we move one row down,
If e==x, we stop or we keep doing this,until we hit the left boundary or the bottom boundary and if we hit a boundary before we find e==x,then the 2d array does not contain that element.
Clearly, the time complexity of this method is O(n) for nXn matrix, but the interviewer insisted on a logrithmic approach, and I was unable to reach anywhere near O(log n).
My question is, can it be done in O(log n)?