Search a 2D Matrix solution explained

When every row of a grid is sorted and each row starts above the previous row's last value, the grid read row by row is one sorted list, so a single binary search over indexes 0 to rows × cols - 1 finds the target, converting each index to a cell with row = i // cols and column = i % cols. That runs in O(log(rows × cols)) time with O(1) extra space.

By Published 8 min read

What the problem gives you

You get a rectangular grid of integers with two ordering rules. Inside each row, values increase from left to right. Across rows, the first value of a row is larger than the last value of the row above it. Given a target, answer true if it appears anywhere in the grid and false otherwise. The intended solution should be logarithmic, not a scan of every cell.

Grid used on this page: [[1, 4, 6], [9, 10, 15], [20, 31, 40]]. Results checked by running the code.
TargetResultWhere the search ends
10trueRow 1, column 1, the middle cell, found on the first check
7falseBetween 6 at the end of row 0 and 9 at the start of row 1
40trueThe last cell
0falseSmaller than every value
Grid used on this page: [[1, 4, 6], [9, 10, 15], [20, 31, 40]]. Results checked by running the code.. Scroll sideways on a small screen.

Ask whether the grid can be empty or have empty rows, whether all rows have the same length, and, most importantly, whether the chaining rule really holds. Many candidates lose time because two different problems share almost the same name: one with chained rows, which this page solves first, and one where only rows and columns are sorted independently, covered further down.

What the interviewer wants to see

This question tests whether you can map a familiar algorithm onto a new shape. The binary search itself is standard; the insight is seeing that the chaining rule makes the whole grid a single sorted sequence, and then handling the index arithmetic cleanly. It is a short problem, so the interviewer will also notice how you test it: a one-row grid, a one-column grid and an empty grid each catch a different bug.

Straightforward first answer

Scan every cell, O(rows × cols). A better first step uses the ordering a little: walk down the rows, and when you find the one whose first and last values bracket the target, check only that row. That is O(rows + cols) with a linear check, or O(rows + log cols) if you binary search the chosen row.

def in_grid_rows(grid, goal):
    for row in grid:
        if row and row[0] <= goal <= row[-1]:
            return goal in row
    return False
Find the bracketing row, then look inside it.

One binary search over the flattened grid

Number the cells 0, 1, 2 and so on, reading left to right and then top to bottom, as if the rows were glued end to end. Because of the chaining rule, values along that numbering never decrease. So you can run an ordinary binary search on the numbers 0 through rows × cols - 1 without building the flat list. To read the value at position i, divide by the row length: the row is i // cols and the column is i % cols.

def in_grid(grid, goal):
    if not grid or not grid[0]:
        return False
    rows, cols = len(grid), len(grid[0])
    low, high = 0, rows * cols - 1
    while low <= high:
        mid = (low + high) // 2
        value = grid[mid // cols][mid % cols]
        if value == goal:
            return True
        if value < goal:
            low = mid + 1
        else:
            high = mid - 1
    return False
Python: binary search on virtual positions, O(log(rows × cols)).
#include <vector>

bool inGrid(const std::vector<std::vector<int>>& grid, int goal) {
    if (grid.empty() || grid[0].empty()) return false;
    const long long rows = grid.size();
    const long long cols = grid[0].size();
    long long low = 0;
    long long high = rows * cols - 1;
    while (low <= high) {
        long long mid = low + (high - low) / 2;
        int value = grid[mid / cols][mid % cols];
        if (value == goal) return true;
        if (value < goal) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return false;
}
C++17: 64-bit positions so rows × cols cannot overflow.

Dividing by the number of columns, not the number of rows, is the detail people most often flip. A quick check: position cols - 1 must map to row 0, last column, and position cols must map to row 1, column 0. On the 3 by 3 grid above, position 4 is row 1, column 1, which holds 10.

An equally valid option is two searches: binary search the first column to find the last row whose first value is at most the target, then binary search that row. The total is O(log rows + log cols), which is the same as O(log(rows × cols)). Some interviewers prefer it because it does not depend on every row having the same length.

When only rows and columns are sorted

In the sibling problem, each row increases left to right and each column increases top to bottom, but a row can start below the previous row's end. The grid is no longer one sorted list, so the flat search breaks. Start at the top-right corner instead. If the value there is larger than the target, nothing below it in that column can match, so step left. If it is smaller, nothing to its left in that row can match, so step down. Each step removes a whole row or column, giving O(rows + cols).

def in_grid_staircase(grid, goal):
    if not grid or not grid[0]:
        return False
    r, c = 0, len(grid[0]) - 1  # start at the top-right corner
    while r < len(grid) and c >= 0:
        value = grid[r][c]
        if value == goal:
            return True
        if value > goal:
            c -= 1  # everything below in this column is even larger
        else:
            r += 1  # everything left in this row is even smaller
    return False
Staircase walk from the top-right corner. Also correct on chained grids.

Starting from the top-left corner does not work, because both moves from there go to larger values and you cannot tell which to take. The bottom-left corner works for the mirrored reason.

Complexity summary

r rows, c columns
ApproachTimeExtra spaceNeeds chained rows?
Check every cellO(r · c)O(1)No
Find the row, scan itO(r + c)O(1)Yes
Flattened binary searchO(log(r · c))O(1)Yes
Search first column, then the rowO(log r + log c)O(1)Yes
Staircase from a cornerO(r + c)O(1)No, only sorted rows and columns
r rows, c columns. Scroll sideways on a small screen.

Edge cases

  • An empty grid, or a grid whose rows are empty: return false before computing any index.
  • One row: the search becomes plain binary search on that row.
  • One column: each row has one value, and every division by cols is division by 1.
  • Target below the first cell or above the last cell.
  • Target that would fall between two rows, like 7 in the grid above.
  • Large grids in C++, Java or Go, where rows × cols can exceed a 32-bit int. Use 64-bit positions.

Mistakes to avoid

  • Mapping position i with the row count instead of the column count, which works only on square grids and hides the bug in most hand tests.
  • Using the flattened search on a grid that is sorted by rows and columns but not chained.
  • Copying the grid into a flat list first, which costs O(r · c) time and space and erases the advantage.
  • Forgetting the empty-grid check and reading grid[0] on an empty list.
  • Testing only on square grids. Always try a 2 by 4 or 4 by 2 grid too.

How to explain it out loud

Fictional example

From grid to list in three sentences
Candidate
Since each row starts after the previous one ends, reading the grid row by row gives one sorted sequence of r times c values.
Candidate
So I binary search positions 0 to r times c minus 1, and convert a position to a cell with integer division and remainder by the number of columns. That is log of r times c, with no extra memory.
Interviewer
What if rows don't chain, only rows and columns are sorted?
Candidate
Then the flat order breaks. I'd start at the top-right corner and step left when the value is too big, down when it is too small. Each step drops a row or a column, so it is r plus c.

Review the halving loop and its boundary rules in Binary Search if the index updates feel shaky. Koko Eating Bananas applies binary search to a range of candidate answers rather than to stored data. The staircase walk is a cousin of the pointer logic in Two Sum on a sorted array, where each move also discards a whole row of candidate pairs. More problems by pattern are on the coding problems hub.

Rehearsing grid search with Natively

Grid problems reward a habit of testing on non-square shapes, so build that into your mock rounds and say each test case aloud. Natively transcribes those sessions on a Mac or Windows computer, so you can review whether you checked a 2 by 4 grid or only the easy square one. When practicing, it can read the grid and constraints from a screenshot and sketch which variant you are facing. See the AI assistant for coding interviews for details.

Questions people ask

How do you solve Search a 2D Matrix in log time?

Because each row starts above the previous row's end, the grid read row by row is one sorted list. Binary search positions 0 to rows times cols minus 1 and read each position as row i // cols, column i % cols.

What is the time complexity of Search a 2D Matrix?

O(log(rows × cols)) for the flattened binary search, which equals O(log rows + log cols). Extra space is O(1).

What if only the rows and columns are sorted?

Then the grid is not one sorted list. Start at the top-right corner and move left when the value is too large or down when it is too small, for O(rows + cols).

Why divide by the number of columns?

Each row holds cols values, so position i is in row i // cols at column i % cols. Dividing by the row count only happens to work on square grids.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP