search-a-2d-matrix.py
binary-search/search-a-2d-matrix.py · Python · 652 B · 2026-02-17 21:02
# Binary search over the whole matrix, using matrix[mid // cols][mid % cols] to access elements. # binary-search # O(log(m*n)) time | O(1) space def searchMatrix(self, matrix: list[list[int]], target: int) -> bool: if len(matrix) == 0: return False rows, cols = len(matrix), len(matrix[0]) left, right = 0, (rows*cols) -1 while left <= right: mid = left + (right - left) // 2 row = mid // cols col = mid % cols val = matrix[row][col] if target < val: right = mid -1 elif target > val: left = mid +1 else: return True return False