Binary Search Over a Row-Chained Sorted Grid
Heaps, Sorting & SearchAuto-graded · 26 test casesLast 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:
- Each row is sorted in non-decreasing order from left to right.
- 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
Trueif any cell holds exactlytarget, otherwise returnFalse. - 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 lengthn1 <= m <= 1001 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight
The two ordering properties together mean that reading the grid row by row — left to right, top to bottom — yields one globally non-decreasing sequence of length m * n. Within a single row the values are sorted. At every row boundary, the first element of the new row is strictly greater than the last element of the previous one, so the ordering never breaks across rows. The entire grid therefore behaves like a single sorted array that has been folded into rows.
Because the underlying sequence is sorted, a standard binary search finds any target in O(log(m * n)) time. The only implementation detail is mapping a flat index k back to a grid cell without building the array explicitly:
- row =
k // n - col =
k % n
Every row holds exactly n elements, so k // n gives the row and k % n gives the offset within that row. Divide and mod by n (the column count), not m.
Algorithm
- Set
lo = 0,hi = m * n - 1. - While
lo <= hi:- Compute
mid = (lo + hi) // 2. - Look up
v = grid[mid // n][mid % n]. - If
v == target, returnTrue. - If
v < target, discard the left half:lo = mid + 1. - If
v > target, discard the right half:hi = mid - 1.
- Compute
- Return
False— the search space is empty and the target was never found.
Why it is correct
Monotonicity. For any flat indices i < j, the value at i is ≤ the value at j. This follows by induction over row boundaries using the two stated properties, so binary search's precondition is satisfied.
Loop invariant. If target is present, at least one occurrence lies within [lo, hi] at every iteration. Discarding [mid+1, hi] when v > target is safe because all cells at indices ≥ mid hold values ≥ v > target. Discarding [lo, mid-1] when v < target is safe symmetrically.
Termination. Every iteration strictly narrows the range (lo increases or hi decreases), so the loop always ends.
Duplicates. The algorithm only needs to find any occurrence, so returning True on the first match is correct even when duplicate values are present.
Edge cases
- Single row (
m = 1):mid // nis always 0; degenerates to a plain binary search over one row. - Single column (
n = 1):mid // 1 = midandmid % 1 = 0; searches down the column. - 1 × 1 grid: one comparison, then the loop ends.
- Target in a gap between rows: the search converges between the two adjacent boundary values and returns
Falsecleanly. - Target below the minimum or above the maximum:
hifalls below 0, orloexceedsm * n − 1, before any access goes out of bounds.
Complexity
| Complexity | |
|---|---|
| Time | O(log(m · n)) — at most ~14 probes for the maximum 10 000-cell grid |
| Space | O(1) — no auxiliary data structure; the flat array is never materialised |
Common mistakes
- Using
mid // mandmid % minstead ofmid // nandmid % n. This only surfaces on non-square grids, so always test withm ≠ n. - Using exclusive-end boundaries (
lo < hi,hi = mid) instead of inclusive ones, which can leave the last element unchecked. - Reaching for a staircase search (start top-right, move left or down). That runs in O(m + n) and is the right tool when only rows and columns are individually sorted — here the stronger row-chaining property makes a fully logarithmic solution possible.
Reference solution
from typing import List
def find_in_chained_grid(grid: List[List[int]], target: int) -> bool:
m, n = len(grid), len(grid[0])
lo, hi = 0, m * n - 1
while lo <= hi:
mid = (lo + hi) // 2
v = grid[mid // n][mid % n] # translate flat index -> (row, col)
if v == target:
return True
if v < target:
lo = mid + 1
else:
hi = mid - 1
return False