AlgoTales · Roadmap

Searching in matrices

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

When every row and every column of a table is sorted, you can search without checking each cell: start at a corner and every comparison lets you drop an entire row or column. A table of a million cells needs only a couple of thousand steps.

Practical use cases

  • Web app: Looking up a fare in a sorted price chart. A bus-booking page keeps a fare chart where prices rise from left to right and from top to bottom, by distance and by class. To find whether a certain fare exists, start at the top-right corner. Too high, move left; too low, move down. The answer appears in a few dozen steps.
  • Web app: Price grid for a shipping calculator. A courier site shows rates by weight band and distance zone, both increasing. Checking whether a quote falls in the chart is a staircase walk that avoids scanning hundreds of cells for every request.
  • System: Sorted tables and range lookups. Databases and map tools store sorted grids, such as elevation tables or range tables, and use the same staircase walk to locate a value without scanning the entire block. Because the walk only moves left or down, the number of steps is about the width plus the height, never the full area, so huge tables stay quick.

The story: Zoya's Staircase of Prices

Zoya's uncle ran a kirana store with a wall shelf of 16 items in a 4 × 4 grid. He had arranged them in a very tidy way: in every row the prices go up from left to right, and in every column the prices go up from top to bottom. Customer asked: "Do you have something that costs exactly 9 rupees?"

Zoya started from the top-left, checking every shelf, like Mira with the lockers. 16 looks in the worst case! Her uncle chuckled. "Stand at the top-right corner instead. From there, one glance tells you which way to go."

The top-right item was 11. Too big! Everything below it in that column is bigger still, so the entire column can be forgotten: step left. Now 7: too small. Everything to its left in that row is smaller still, so the entire row is forgotten: step down. Left or down, left or down, every step threw away a whole row or column.

In just a few steps she reached 9, like walking down a staircase. This is the staircase search for a sorted matrix: start at a corner where one direction grows and the other shrinks, and each comparison removes an entire line of the grid.

How to spot this problem, and where you need it

You have a grid where rows and columns are both sorted, and you need to find a value or count values quickly, but scanning every cell feels wasteful.

Signs you need it

  • The data is a table where each row increases left to right and each column increases top to bottom, like fare, rate and price charts.
  • The problem says search in a sorted matrix, and lists matrix sizes in the thousands.
  • You are running a nested loop over rows and columns to find one value in a sorted table.

Where to use it in a project

  • Pricing, shipping and fare tables with two increasing dimensions, such as weight bands and distance zones.
  • Lookup features over sorted grids of scores, grades or measurements loaded in memory.

The solution

Start at the top-right cell. Compare it with the target. If it equals the target, you are done. If the cell is bigger, the whole column below it is also bigger, so move one step left. If the cell is smaller, the whole row to its left is also smaller, so move one step down. Stop if you leave the grid. You never go back, so the walk is short.

Payoff: Before: checking up to 1,000,000 cells in a 1,000 by 1,000 grid. After: at most about 2,000 steps.

Explain it like I am 8

Imagine a staircase of price tags. Stand at the top-right. If the tag is too expensive, walk left to cheaper tags. If it is too cheap, walk down to more expensive tags. You never walk back, and soon you find the price or run out of shelf.

How it works, step by step

  1. Make sure the matrix is sorted in both directions: rows rise to the right and columns rise downward.
  2. Stand at the top-right cell: r = 0, c = cols - 1.
  3. If the cell equals the target, you are done.
  4. If the cell is bigger than the target, discard this whole column: c--.
  5. If the cell is smaller, discard this whole row: r++. Stop when you step off the grid: the target is not there.

The code in four languages

PHP

<?php
// Staircase search in a matrix sorted along rows and along columns
function searchMatrix(array $m, int $target): ?array {
    $r = 0;
    $c = count($m[0]) - 1;                    // start at the top-right
    while ($r < count($m) && $c >= 0) {
        $v = $m[$r][$c];
        if ($v === $target) return [$r, $c];  // found
        if ($v > $target) $c--;               // too big: drop this column
        else $r++;                            // too small: drop this row
    }
    return null;                              // walked off the grid
}

$shelf = [[1, 4, 7, 11], [2, 5, 8, 12], [3, 6, 9, 16], [10, 13, 14, 17]];
echo json_encode(searchMatrix($shelf, 9)) . PHP_EOL;    // [2,2]
echo json_encode(searchMatrix($shelf, 15)) . PHP_EOL;   // null

JavaScript

// Staircase search in a matrix sorted along rows and along columns
function searchMatrix(m, target) {
  let r = 0;
  let c = m[0].length - 1;                    // start at the top-right
  while (r < m.length && c >= 0) {
    const v = m[r][c];
    if (v === target) return [r, c];          // found
    if (v > target) c--;                      // too big: drop this column
    else r++;                                 // too small: drop this row
  }
  return null;                                // walked off the grid
}

const shelf = [[1, 4, 7, 11], [2, 5, 8, 12], [3, 6, 9, 16], [10, 13, 14, 17]];
console.log(JSON.stringify(searchMatrix(shelf, 9)));    // [2,2]
console.log(JSON.stringify(searchMatrix(shelf, 15)));   // null

Java

import java.util.*;

public class Main {
    // Staircase search in a matrix sorted along rows and along columns
    static int[] searchMatrix(int[][] m, int target) {
        int r = 0;
        int c = m[0].length - 1;                       // start at the top-right
        while (r < m.length && c >= 0) {
            int v = m[r][c];
            if (v == target) return new int[]{r, c};   // found
            if (v > target) c--;                       // too big: drop this column
            else r++;                                  // too small: drop this row
        }
        return null;                                   // walked off the grid
    }

    public static void main(String[] args) {
        int[][] shelf = {{1, 4, 7, 11}, {2, 5, 8, 12}, {3, 6, 9, 16}, {10, 13, 14, 17}};
        System.out.println(Arrays.toString(searchMatrix(shelf, 9)));    // [2, 2]
        System.out.println(Arrays.toString(searchMatrix(shelf, 15)));   // null
    }
}

Go

package main

import "fmt"

// searchMatrix does a staircase search in a matrix sorted along rows and columns.
func searchMatrix(m [][]int, target int) (row, col int, found bool) {
	r := 0
	c := len(m[0]) - 1 // start at the top-right
	for r < len(m) && c >= 0 {
		v := m[r][c]
		if v == target {
			return r, c, true // found
		}
		if v > target {
			c-- // too big: drop this column
		} else {
			r++ // too small: drop this row
		}
	}
	return 0, 0, false // walked off the grid
}

func main() {
	shelf := [][]int{{1, 4, 7, 11}, {2, 5, 8, 12}, {3, 6, 9, 16}, {10, 13, 14, 17}}
	fmt.Println(searchMatrix(shelf, 9))  // 2 2 true
	fmt.Println(searchMatrix(shelf, 15)) // 0 0 false
}

Time: O(rows + cols) · Extra space: O(1). Each step removes one row or one column, so at most rows + cols steps. Scanning every cell would be rows × cols.

Watch out for

  • Starting at the top-left (or bottom-right). There, both directions grow, so one comparison cannot tell you which way to go.
  • Using this on a matrix that is sorted only by rows. If each row starts bigger than the previous row ends, a binary search over the flattened grid is the better tool.
  • Moving the wrong way: too big means go left, too small means go down.

Quick check

  1. Why start at the top-right corner?
    • It is the biggest cell
    • One direction grows and the other shrinks, so each comparison picks a direction
    • It is the closest to the target
  2. The current cell is bigger than the target. What next?
    • Move down
    • Move left
    • Stop
  3. How many steps does the walk take at most for an R × C grid?
    • R × C
    • R + C
    • Only R