You are given an m x n integer matrix matrix with the following two properties:
Given an integer target, return true if target is in matrix or false otherwise.
You must write a solution in O(log(m * n)) time complexity.
m == matrix.lengthn == matrix[i].length1 <= m, n <= 100-10000 <= matrix[i][j], target <= 10000The brute force approach simply checks every element in the matrix one by one.
Since the matrix is sorted but we're ignoring that structure, we just scan through all rows and all columns until we either find the target or finish searching.
true.false if the target was not found.Since each row is sorted left-to-right and each column is sorted top-to-bottom, we can search smartly instead of checking every cell.
Start at the top-right corner:
This works like walking down a staircase—each step eliminates an entire row or column. We keep moving until we either find the target or move out of bounds.
Because each row of the matrix is sorted, and the rows themselves are sorted by their first and last elements, we can apply binary search twice:
This eliminates large portions of the matrix at each step and uses the sorted structure fully.
Because the matrix is sorted row-wise and each row is sorted left-to-right, the entire matrix behaves like one big sorted array.
If we imagine flattening the matrix into a single list, the order of elements doesn't change.
This means we can run one binary search from index 0 to ROWS * COLS - 1. For any mid index m, we can map it back to the matrix using:
m // COLSm % COLSThis lets us access the correct matrix element without actually flattening the matrix.
When converting a 1D index to 2D coordinates in the one-pass binary search approach, it is easy to mix up row = m // COLS and col = m % COLS. Using ROWS instead of COLS in these formulas will produce incorrect indices and lead to wrong answers or out-of-bounds errors.
In the two-pass binary search approach, after identifying the candidate row, forgetting to recalculate row = (top + bot) // 2 before the second binary search can cause you to search in the wrong row. Similarly, checking top <= bot incorrectly after the first loop can lead to false negatives.
Failing to check if the matrix is empty or if any row is empty before accessing matrix[0] will cause runtime errors. Always validate that both ROWS > 0 and COLS > 0 before proceeding with the search.
Discussion
…