KatInterview

Binary Search Over a Row-Chained Sorted Grid

Heaps, Sorting & SearchAuto-graded · 26 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraysmatrix

Last updated

Tests whether a candidate can exploit strict row-chaining in a sorted matrix to locate a target value in O(log(m·n)) time using a single binary search.

You have an m × n grid of integers that satisfies two guarantees:

  1. Each row is sorted in non-decreasing order from left to right.
  2. The first element of every row is strictly greater than the last element of the row above it.

Given a target integer, determine whether it appears anywhere in the grid.

Rules

  • Return True if any cell holds exactly target, otherwise return False.
  • Both ordering guarantees always hold for the input; you do not need to verify them.
  • Aim for a solution whose running time is logarithmic in the total number of cells (m * n).

Constraints

  • m == len(grid) and every row has the same length n
  • 1 <= m <= 100
  • 1 <= n <= 100
  • -10^4 <= grid[i][j] <= 10^4
  • -10^4 <= target <= 10^4

Examples

Example 1

Input: find_in_chained_grid([[2, 4, 9], [11, 15, 18], [21, 30, 41]], 15)

Output: True

Example 2

Input: find_in_chained_grid([[2, 4, 9], [11, 15, 18], [21, 30, 41]], 10)

Output: False

Example 3

Input: find_in_chained_grid([[-3, -3, 0]], -3)

Output: True

Hints

Hint 1

Reading the grid row by row produces a single non-decreasing sequence. Why does the strict between-row condition guarantee that the boundary between rows never breaks the order?

Hint 2

If you number the cells 0 through m*n-1 from left to right, top to bottom, you can treat them as a flat sorted array. For a flat index k, which row and column does it map to when every row has n elements?

Hint 3

Run a standard binary search on that virtual flat array, translating each midpoint index back to (row, col) on the fly. No extra memory is needed.