Binary Search
40 / 170Binary SearchLesson 2 of 8About 33 min
Any structure you can index in order can be binary searched, including a grid.
With that mapping, searching the grid is the ordinary boundary loop with one substitution.
def grid_contains(grid, target): if not grid or not grid[0]: return False rows, cols = len(grid), len(grid[0]) low, high = 0, rows * cols while low < high: mid = low + (high - low) // 2 value = grid[mid // cols][mid % cols] if value >= target: high = mid else: low = mid + 1 return low < rows * cols and grid[low // cols][low % cols] == target print(grid_contains([[1, 3, 5], [7, 9, 11]], 9))print(grid_contains([[1, 3, 5], [7, 9, 11]], 4))A grid has 3 columns. Using reading order numbered from 0, which cell is position 7?
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.