Free beta: 60 days of full access, no card needed.84 seats leftSign up free

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy

All patterns

Matrix search (sorted grid)

O(m+n)

In a grid sorted both ways, one corner can only move in a single direction. Each comparison drops a whole row or column.

Updated Oct 17, 2026

How does Matrix search (sorted grid) work?

There are two kinds of sorted grid. In one each row continues the previous, in the other rows and columns merely rise.

The first kind is a sorted list folded into rows. Binary search over r times c positions.

For the second kind, start at the top-right corner. Everything to its left is smaller and everything below is larger.

If the value there is too large, move left. That drops the whole column at once.

If it is too small, move down. That drops the whole row.

Every step removes one row or one column. So the walk ends within r plus c steps.

Sources: Wikipedia: Binary search

  1. start at 7, top rightLooking for 5 in a grid that rises both ways.
  2. 7 is too largeEverything below 7 in that column is larger. Move left.
  3. 4 is too smallEverything left of 4 in that row is smaller. Move down.
  4. now at 5The value under the walk matches the target.
  5. three stepsNine cells, three comparisons. Two lines were dropped whole.
Finding 14 in a grid sorted both ways
searchMatrix([[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]], 14)
matrix: every row and every column rises
01234
01471115
12581219
23691622
31013141724
41821232630
row = 0col = 4target = 14steps = 0

Is 14 in the matrix? Start at the top-right corner: everything to its left is smaller, everything below it is larger.

Speed race
Find one value in the same 6 by 8 sorted grid

Bars: the 48 cells of the grid laid out row after row; every row and every column grows. The target is in the bottom row. In the size table n is the number of cells in a square grid.

One operation is one cell checked. Every frame, each lane does the same number of operations, so the slow one falls behind.

Scan every cell O(m·n)
0 operations
Staircase search O(m + n)
0 operations

 

And with more numbers

Operations for n numbers, and roughly how long they take at 100 million simple operations a second. An estimate from the same count, not a measurement.

n = 1,000
Scan every cell1K · under 1 ms
Staircase search63.2 · under 1 ms
n = 100,000
Scan every cell100K · 1 ms
Staircase search632.5 · under 1 ms
n = 10,000,000
Scan every cell10M · 100 ms
Staircase search6.3K · under 1 ms

The Matrix search (sorted grid) code template

function searchMatrix(matrix, target) {
    let row = 0;
    let col = matrix[0].length - 1;
    while (row < matrix.length && col >= 0) {
        const v = matrix[row][col];
        if (v === target) return true;
        if (v > target) col--;
        else row++;
    }
    return false;
}

A worked example of Matrix search (sorted grid)

The kth smallest value in a sorted grid

A grid has rows and columns that both rise. Return its kth smallest value.

Flattening and sorting works, but it reads every cell.

Binary search over the range of values, not over the positions.

For a candidate value, count how many cells are not larger. That count says which half to keep.

function kthSmallest(matrix, k) {
    const n = matrix.length;
    let lo = matrix[0][0];
    let hi = matrix[n - 1][n - 1];

    const countNotAbove = (value) => {
        let count = 0;
        let row = n - 1;

        // one staircase walk, starting from the bottom-left corner
        for (let col = 0; col < n; col++) {
            while (row >= 0 && matrix[row][col] > value) row--;
            count += row + 1;
        }

        return count;
    };

    while (lo < hi) {
        const mid = lo + Math.floor((hi - lo) / 2);
        if (countNotAbove(mid) >= k) hi = mid;
        else lo = mid + 1;
    }

    return lo;
}

When should you use Matrix search (sorted grid)?

Use Matrix search (sorted grid) when the problem statement says “matrix sorted along both rows and columns”, “search for a value in a 2D sorted grid” or “start from a corner and eliminate a row or column”. A solution built on it usually runs in O(m+n).

  • matrix sorted along both rows and columns
  • search for a value in a 2D sorted grid
  • start from a corner and eliminate a row or column
  • row and column both monotonic

The signal words of every pattern sit in one table, the algorithm patterns cheat sheet.

What is Matrix search (sorted grid) confused with?

Matrix search (sorted grid) is most often confused with Binary search (array), Two pointers (opposite ends), Matrix traversal (spiral / diagonal) and Linear search.

Common mistakes with Matrix search (sorted grid)

  • Starting from the wrong corner

    The top-left cell is smaller than both neighbours, so it gives no direction. Start top-right or bottom-left.

  • Treating a row-wise grid as fully sorted

    Searching by position needs each row to continue the last. Check that before flattening.

  • Sorting the whole grid

    That throws away the structure you were handed. It also costs rc log rc.

  • Returning the middle candidate

    In a value search the answer must be a value that exists. Squeeze until the bounds meet.

Interview problems solved with Matrix search (sorted grid) include Search a 2D matrix, Search a 2D matrix II, Kth smallest in a sorted matrix, Find a peak element II, Count negative numbers in a sorted matrix, Median of a row-wise sorted matrix and Smallest common element in all rows.

  • Search a 2D matrix: One sorted list folded into rows.
  • Search a 2D matrix II: The staircase walk from a corner.
  • Kth smallest in a sorted matrix: Binary search over values, counting per candidate.
  • Find a peak element II: Binary search over the columns.
  • Count negative numbers in a sorted matrix: The same staircase, counting instead of matching.
  • Median of a row-wise sorted matrix: Count how many cells are not above a candidate.
  • Smallest common element in all rows: One pointer per row, moved together.

What is the time and space complexity of Matrix search (sorted grid)?

The target complexity of Matrix search (sorted grid) is O(m+n).

An r by c grid gives O(r + c) for the staircase walk. A fully sorted grid allows O(log rc).

See where this fits in the 150-step track