skip to content

When does binary searching every row of a row- and column-sorted grid beat the O(m+n) walk?

level: seniorimportance: should knowfreq 40%

answer

  1. write both costs as expressions
  2. the row count multiplies the logarithm
  3. which dimension is inside the log?
  4. try four by a million, then flip it
  5. short and wide versus tall and narrow

basics

~20 s

Per-row binary search costs O(m log n) and beats the O(m+n) corner walk only on short, wide grids — few rows, many columns — because the row count multiplies the logarithm. On tall or square grids the walk wins outright.

solid answer

~50 s

Compare the two expressions rather than the words: the corner walk is m + n and per-row binary search is m·log n. Per-row search wins when m·log n < m + n, which rearranges to m·(log n − 1) < n — that is, when the grid is much **wider** than it is tall. A 4 x 1,000,000 grid takes roughly 80 probes per-row against a million for the walk. Flip the shape to 1,000,000 x 8 and per-row search costs about three million probes against a million for the walk, so the walk wins. On a square grid, n·log n against 2n makes the walk win as well. The trap is the instinct that "log beats linear": the logarithm here is on the column count only, and the row count multiplies it. Worth adding: per-row search never uses the column ordering, so it is also the right method when only rows are sorted.

go deeper

for a junior

Know both costs by name: the corner walk is about m + n probes and binary searching each row is about m times log n. Recognise that which is smaller depends on the grid's shape.

for a middle

Explain the comparison by substitution — plug in a short wide grid and a tall narrow one and show the winner flipping — and say why the row count sitting outside the logarithm is the decisive detail.

for a senior

Choose and defend a method from the measured aspect ratio and the cost of a single probe, name the regime where probe count is the latency budget, and state what evidence would flip your choice.

for a principal

Own the call between branching on run-time dimensions, standardising on one method for maintainability, and paying for a more elaborate strategy. Argue when the reduced probe count is worth the code nobody on the team wants to own.

## Two costs, written out For an m x n grid sorted along every row and every column, three methods are on the table: | Method | Probes | Uses column ordering? | Extra space | |---|---|---|---| | Scan every cell | m·n | no | O(1) | | Corner elimination from the top-right | m + n | yes | O(1) | | Binary search each row | m·log n | no | O(1) | The interview question is almost never "which is fastest" in the abstract; it is "under which shapes does each one win", because that is where a candidate reveals whether they read asymptotics as slogans or as arithmetic. ## Solving the comparison Per-row binary search beats the corner walk exactly when ``` m * log n < m + n ``` which rearranges to `m * (log n - 1) < n`. Read it directly: the row count sits **outside** the logarithm and multiplies it, so it is the row count that decides. The method wins when m is small relative to n / log n — a short, wide grid. Concrete shapes, using base-2 logarithms: | Shape | Corner walk (m+n) | Per-row search (m·log n) | Winner | |---|---|---|---| | 4 x 1,000,000 | ~1,000,004 | ~80 | per-row, by four orders of magnitude | | 1,000 x 1,000 | ~2,000 | ~10,000 | corner walk | | 1,000,000 x 8 | ~1,000,008 | ~3,000,000 | corner walk | The middle row is the one that matters most in practice: on a square grid — the default mental image — the corner walk wins, which is why it is taught as the answer. But the answer is conditional, and a senior candidate says so. ## The misconception being tested The reflex is "logarithmic beats linear, so binary search wins". Two things are wrong with it. First, `m·log n` is not logarithmic in the input size at all; it is *linear in the row count*, with a logarithmic factor attached. Second, `m + n` is not linear in the cell count either — it is linear in the grid's **perimeter**, which is already an enormous saving against m·n. Comparing an O(m log n) label to an O(m+n) label without substituting the actual dimensions is exactly the failure mode. Asymptotic notation compares growth in *one* parameter; with two parameters you must decide how they relate before any comparison is meaningful. ## What per-row search quietly gives up, and gains It never consults the column ordering. That is a loss — it throws away half the guarantee — but it is also a gain in applicability: the method remains correct on a grid where only the rows are sorted and columns are arbitrary, which the corner walk cannot handle at all. If a data contract promises only per-row ordering, per-row binary search is not a fallback, it is the method. When the column ordering *does* hold, you can prune before searching. The first entries of the rows are non-decreasing top to bottom, and so are the last entries; therefore the rows that could possibly contain the target — those whose first entry does not exceed it and whose last entry is not below it — form a **contiguous band**. Two binary searches over the row boundaries, O(log m) each, locate that band. In practice this often shrinks the work enormously. It does not improve the worst case: an adversarial grid can put every row in the band, leaving m·log n again. ## Choosing under a real constraint When a probe is cheap — the grid is a small in-memory block — probe counts barely matter and either method is fine; pick the one you can explain and test. When each probe is expensive, because a cell fetch crosses a network or a storage boundary, the probe count *is* the latency budget and the shape analysis above becomes the deciding argument. State which regime you are in before you pick, and say what would change your mind: for a grid whose aspect ratio varies at run time, the honest answer is to branch on the measured dimensions rather than hard-code one method. Neither simple method is optimal for every aspect ratio. More elaborate divide-and-conquer strategies do better than both on strongly skewed shapes; they are rarely worth the implementation and testing cost unless the search is genuinely hot, and knowing where that line sits is the judgment being examined. ## What a strong answer sounds like "The corner walk is m + n and per-row binary search is m·log n, so the question is the aspect ratio. For anything near-square or taller than wide, the walk wins and I would default to it. For a short, wide grid — a handful of rows across a very long span — per-row search wins by orders of magnitude, and I would also reach for it if the contract only promises row ordering. If the column ordering holds I would first narrow to the contiguous band of candidate rows in logarithmic time, which usually collapses the constant even though it does not change the worst case."

  • Give the shape where per-row binary search loses badly to the corner walk.
    Tall and narrow. At 1,000,000 rows by 8 columns, per-row search runs about three million probes — a million binary searches of three steps each — while the walk retires a line per probe and finishes in roughly a million. The logarithm cannot rescue a factor of m that the walk simply does not pay.
  • Does the column ordering help per-row binary search at all?
    Yes, as a filter rather than a change of method. Both the first entries and the last entries of the rows are non-decreasing downward, so the rows that could hold the target form a contiguous band locatable with two logarithmic searches. It usually shrinks the constant dramatically but leaves the worst case at m·log n.
  • Why is comparing the labels O(m log n) and O(m+n) not enough to decide?
    Because they are functions of two independent parameters. Asymptotic ordering is only defined once you fix how m and n relate — as m/n varies, the winner flips. You have to substitute the real dimensions, or state the regime, before either label ranks above the other.

saying these in an interview costs you the question

  • Says logarithmic always beats linear so per-row search always wins
  • Ignores that the row count multiplies the logarithm
  • Compares the two bounds without substituting real dimensions
  • Claims the corner walk is optimal for every aspect ratio
  • Forgets that per-row search works when only rows are sorted

context