Binary Search on Matrix

To determine which row to search, you can check the last element of each row. This can be achieved by using binary search. Then binary search in that row to find the element.

    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int m = matrix.length, n = matrix[0].length;
        int row = findRow(matrix, target, 0, m - 1);
        int left = 0, right = n - 1;
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (matrix[row][mid] == target) {
                return true;
            } else if (matrix[row][mid] < target) {
                left = mid;
            } else {
                right = mid;
            }
        }
        return matrix[row][left] == target || matrix[row][right] == target;
    }
    
    private int findRow(int[][] matrix, int target, int top, int bottom) {
        int last = matrix[0].length - 1;
        while (top + 1 < bottom) {
            int mid = top + (bottom - top) / 2;
            if (matrix[mid][last] >= target) {
                bottom = mid;
            } else {
                top = mid;
            }
        }
        if (target <= matrix[top][last]) {
            return top;
        }
        return bottom;
    }

1. BFS, starting from top left node, traverse to right and down direction on each node, until find the target.

T: O(m *n) S: O(m*n) TLE

2. Divide and Conquer, Divide the matrix into 4 subregion:

  • matrix[mid_row][mid_col] == target: return true

  • matrix[mid_row][mid_col] > target: search in region 1,2,3

  • matrix[mid_row][mid_col] < target: search in region 2,3,4

T: O((MN)log4(3)) because the recursive equation of this solution is T(n) = 3T(n/4) + O(1).

It reduces the problem by 3/4 every function call. The base case would be a 1 x 1 matrix. So

mn * (3/4)^x = 1,

thus we have x = log(3/4, 1/mn) = log(4/3, mn) a=ba = b

Thus,

T(m * n) = O(lg(mn)) = O(lg(m) + lg(n))

3. Search Space Reduction

Starts from top-right element, move down if matrix[row][col] < target, move left if matrix[row][col] > target.

T: O(m + n)

Binary Search between the max and min elements in the matrix. The min is the top-left element, max is the bottom-right element. Each search, take the mid as a threshold, and count how many elements are smaller than the threshold.

T: O(N * log(max - min)) S: O(1)

Last updated