Asked at Graviton Research Capital
Theory: Algorithms Under a Complexity BoundRead the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.
Available in Python and C++. You are solving it in C++. Switch to Python
A grid of numbers is sorted two ways: every row is non-decreasing from left to right, and every column is non-decreasing from top to bottom. Decide whether a target value appears anywhere in it.
Reading every cell works, but it costs \(R \times C\) steps for an \(R \times C\) grid. The two orders together let you do it in \(O(R + C)\): each comparison should rule out a whole row or a whole column.
Implement search_sorted_grid(grid, target) returning True when target
is in the grid and False otherwise. The grid may be empty, or have rows of
length zero; neither contains anything.
grid = [
[1, 4, 7, 11],
[2, 5, 8, 12],
[3, 6, 9, 16],
[10, 13, 14, 17],
]
search_sorted_grid(grid, 5)
# True
search_sorted_grid(grid, 15)
# False (no row or column contains 15)
bool search_sorted_grid(const std::vector<std::vector<long long>>& grid,
long long target);