Faaez Razeen

Search a 2D Matrix

  • 2 min read
  • LC-Medium
  • Binary-search

3 years ago

Solution

TimeSpaceExplanation
O(log m + log n)O(1)
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: nrows, ncols = len(matrix), len(matrix[0]) top, bottom = 0, nrows - 1 while top <= bottom: row = (top + bottom) // 2 if target > matrix[row][-1]: top = row + 1 elif target < matrix[row][0]: bottom = row - 1 else: break if not (top <= bottom): return False left, right = 0, ncols - 1 while left <= right: col = (left + right) // 2 if target > matrix[row][col]: left = col + 1 elif target < matrix[row][col]: right = col - 1 else: return True return False