All topics
140

Search a sorted matrix from a corner

Tier 1Locked

Where it runs

1. The problem

You have a grid of numbers, and the numbers in it are in order. In every row they grow from left to right. In every column they grow from top to bottom. You are given a target number and must answer one question: is it in the grid or not?

The simplest way is to look at every cell. In a big grid that is slow. The order of the numbers lets you skip almost every cell and reach the answer along one short path.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included
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

Recognise it

Matrix search (sorted grid)

Say these words and it is this pattern

  • 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

Looks similar, isn't

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

On LeetCode

Problems on a grid whose rows and columns are both sorted, asking whether a value is there or how many values sit below some line. Start at the top-right corner, and each comparison drops a row or a column, O(rows + cols).

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