Search in 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

(Java Code on github at the bottom of the post. )

My thoughts and solutions:

Well I guess anyone knows binary search can think of a straightforward solution: just think of this matrix as a long array with m*n elements and apply binary search on it. So it takes O(logmn) = O(logm) + O(logn) But we should probably ask: is m*n still in the range of Integer in Java? If true, good. Go ahead.

If not, and if m and n are in the range of Integer in Java, we could do it in another way: use two passes of binary search, one to locate the possible row that the target could reside in, and the other to search the target on that row. But this one is a bit tricky and be sure to check boundary cases.

Code on github:

Enhanced by Zemanta