Skip to content

Locating a value in a row- and column-sorted grid

Question

An m×nm\times n matrix has every row sorted increasing from left to right and every column sorted increasing from top to bottom. How do you search it for a given value, and what is the cost?

Short answer

Start at the top-right corner: O(m+n)O(m+n). If the entry equals the target you are done; if it is larger, move left (everything below in that column is larger too); if smaller, move down (everything left in that row is smaller). Each step discards a whole row or column, so at most m+n−1m+n-1 steps are needed.

Adapted from Zhou, A Practical Guide to Quantitative Finance Interviews, sec. 7.1 Algorithms, 'Search algorithm C', p.177; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question