A warehouse labels its shelves with ID numbers laid out in a grid of m rows and n columns. Reading the grid row by row, left to right and top to bottom, the IDs are strictly increasing: each row is sorted, and the first ID of a row is larger than the last ID of the row above it.
Write grid_contains(grid: list[list[int]], target: int) -> bool that returns True if target appears in the grid.
grid = [[2, 5, 9, 11],
[14, 20, 21, 30],
[33, 40, 47, 52]]
grid_contains(grid, 21) # True
grid_contains(grid, 12) # False (it would sit between 11 and 14)
grid_contains(grid, 52) # True
grid_contains([[7]], 3) # False
1 <= m, nandm * n <= 10^6; values are in[-10^9, 10^9].- The tests run thousands of lookups on one big grid, so each lookup must be O(log(m * n)). Scanning cells, or even scanning down the rows to find the right one, is too slow. Don't use
inon a row or thebisectmodule. - C++ / Java: you write
gridContainsAll(grid, targets), which returnsgridContains(grid, t)for everytintargets, in order, so the tests can run many lookups on one big grid. WritegridContainsas a helper and call it in a loop.
Show hint
if you numbered the cells 0 .. m*n - 1 in reading order, the values would form one sorted list. Which row and column does cell number k live in?