You are given an m × n integer matrix where 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. Given an integer target, return true if target is in the matrix, or false otherwise. Must run in O(log(m × n)) time.
matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3truematrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13falsematrix = [[1,1]], target = 0falselo=0, hi=m*n-1lo ≤ hi; compute mid=(lo+hi)/2mid → matrix[mid/n][mid%n], get valval==target → return trueval < target → lo=mid+1 (eliminate left half)hi=mid-1 (eliminate right half)lo > hi: search exhausted → return falseBecause each row is sorted and every row starts after the previous row ends, flattening the matrix gives a fully sorted 1D array. A virtual index mid maps bijectively to cell (mid/n, mid%n). Standard binary search then finds the target in O(log(m·n)) steps — equivalent to binary-searching an array of length m×n.
Checking every cell is O(m) times n. But the rules mean the whole matrix is one sorted list, read row by row.
Binary search over positions 0 to m times n −1. Turn a position into a cell with row equal to position divided by the number of columns, and column equal to position mod the number of columns.
A matrix sorted row after row is one long sorted array. Divide and mod by the column count to find the cell.
Run the animation above on your own input, or watch the 1:25 video explanation of Search a 2D Matrix with a dry run and Java code.