Given a 2d array sorted in increasing order from left to right and top to bottom, what is the best w

Posted by Phukab on Stack Overflow See other posts from Stack Overflow or by Phukab
Published on 2010-03-16T20:18:01Z Indexed on 2010/03/16 20:21 UTC
Read the original article Hit count: 147

I was recently given this interview question and I'm curious what a good solution to it would be.

Say I'm given a 2d array where all the numbers in the array are in increasing order from left to right and top to bottom.

What is the best way to search and determine if a target number is in the array?

Now, my first inclination is to utilize a binary search since my data is sorted. I can determine if a number is in a single row in O(log N) time. However, it is the 2 directions that throw me off.

Another solution I could use, if I could be sure the matrix is n x n, is to start at the middle. If the middle value is less than my target, then I can be sure it is in the left square portion of the matrix from the middle. I then move diagnally and check again, reducing the size of the square that the target could potentially be in until I have honed in on the target number.

Does anyone have any good ideas on solving this problem?

Example array:

Sorted left to right, top to bottom.

1 2 4 5 6  
2 3 5 7 8  
4 6 8 9 10  
5 8 9 10 11  

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about interview-questions