A 2D matrix with a clever property: treat it as a single sorted array and run standard binary search. One index mapping trick does all the work.
Given an m x n integer matrix where each row is sorted left-to-right and the first integer of each row is greater than the last integer of the previous row, return true if target is in the matrix. Must run in O(log(m × n)).
Because every row is sorted and the first element of each row is greater than the last element of the previous row, the entire matrix is effectively one long sorted array — just arranged in 2D. We binary search this virtual 1D array and convert each mid index to a row/column on the fly.
For a matrix with cols columns, virtual index mid maps to:
Search space: left = 0, right = m*n - 1. The rest is identical to LC 704 — just swap nums[mid] with matrix[mid/cols][mid%cols].
class Solution { public boolean searchMatrix(int[][] matrix, int target) { int m = matrix.length, n = matrix[0].length; int left = 0, right = m * n - 1; while (left <= right) { int mid = left + (right - left) / 2; int val = matrix[mid / n][mid % n]; // 1D → 2D mapping if (val == target) return true; else if (val < target) left = mid + 1; else right = mid - 1; } return false; } }
class Solution: def searchMatrix(self, matrix: list[list[int]], target: int) -> bool: m, n = len(matrix), len(matrix[0]) left, right = 0, m * n - 1 while left <= right: mid = left + (right - left) // 2 val = matrix[mid // n][mid % n] # 1D → 2D mapping if val == target: return True elif val < target: left = mid + 1 else: right = mid - 1 return False