Medium dsa binary-search

Search a 2D Matrix

The 30 second answer

Each row is sorted, and the first value of a row is greater than the last value of the previous row, so the matrix is a single sorted sequence in row-major order. I binary-search the range 0 to rows times columns minus 1, and I map mid to row mid / columns and column mid % columns.

Could you say this in an interview?

Problem Write an efficient algorithm that searches for a target in an m by n matrix. Each row is sorted in non-decreasing order, and the first integer of each row is greater than the last integer of the previous row. Original: LeetCode 74: Search a 2D Matrix.

Understanding the prompt The second condition is what lets you treat the matrix as one sorted array of length m * n. Without it, as in Search a 2D Matrix II, you need a different walk from a corner. You only need a yes or no.

Pattern recognition Classic binary search after flattening a 2D index into 1D.

Brute force Scan every cell: O(m * n). Binary search each row: O(m log n), which is correct but slower than one search on the whole length.

Optimal lo = 0, hi = m * n - 1. mid maps to matrix[mid / n][mid % n], where n is the column count. Then it is ordinary exact-match binary search. Empty matrices are excluded by the official constraints; still be ready to discuss a 0-row or 0-column input.

Alternatives Binary-search the row first, then the column, which is two logarithmic searches and also O(log m + log n). The flattened form is one loop and the same complexity.

Java solution

public class SearchA2DMatrix {
    static boolean searchMatrix(int[][] matrix, int target) {
        int rows = matrix.length, cols = matrix[0].length;
        int lo = 0, hi = rows * cols - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            int val = matrix[mid / cols][mid % cols];
            if (val == target) return true;
            if (val < target) lo = mid + 1;
            else hi = mid - 1;
        }
        return false;
    }

    public static void main(String[] args) {
        var m = new int[][] {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
        System.out.println(searchMatrix(m, 3));  // true
        System.out.println(searchMatrix(m, 13)); // false
    }
}

Complexity O(log(m * n)) time, O(1) extra space.

Edge cases

  • Official sample [[1,3,5,7],[10,11,16,20],[23,30,34,60]] returns true for 3 and false for 13.
  • The target is the first or last cell.
  • A one-row or one-column matrix reduces to ordinary binary search.

Follow-ups

  • Search a 2D Matrix II, where rows and columns are sorted but the row starts are not above the previous row end: start at a corner and walk in O(m + n).

Tests The official 3 by 4 matrix returns true for target 3 and false for target 13.

How to say it in the interview "The matrix is one sorted sequence in row-major order, so I binary-search the range 0 to m times n minus 1 and map mid to row mid / n and column mid % n. Logarithmic in the number of cells."

Sources (1)
  1. LeetCode 74: Search a 2D Matrixleetcode.com