Binary Search · Pattern 5 of 8

Searching a sorted 2D matrix

Two shapes. A matrix sorted row after row is one long sorted array: binary search the flattened index. A matrix sorted by row and by column is searched by stepping from a corner.

2 variations · 4 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Each row is sorted, and each row starts after the previous one ends
  • Rows sorted left to right and columns sorted top to bottom
  • A binary matrix whose rows are sorted (0s then 1s)

The template

2D Binary Search + Step Search
// rows and columns sorted: start at the top-right corner
boolean searchMatrix(int[][] m, int target) {
    int r = 0, c = m[0].length - 1;
    while (r < m.length && c >= 0) {
        if (m[r][c] == target) return true;
        if (m[r][c] > target) c--;     // the rest of this column is bigger
        else r++;                      // the rest of this row is smaller
    }
    return false;
}

// fully sorted (row after row): index k is cell (k / cols, k % cols)
boolean searchFlat(int[][] m, int target) {
    int rows = m.length, cols = m[0].length, lo = 0, hi = rows * cols - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2, v = m[mid / cols][mid % cols];
        if (v == target) return true;
        if (v < target) lo = mid + 1; else hi = mid - 1;
    }
    return false;
}

The variations

  1. 1Flatten the matrix

    When every row starts after the previous one ends, the matrix is a sorted array of length rows × cols. Map index k to (k / cols, k % cols) and run the normal search.

  2. 2Step search from a corner

    From the top-right, moving left makes values smaller and moving down makes them bigger, so every comparison removes a row or a column: O(m + n). Rows of 0s then 1s work the same way.

Mistakes to avoid

  • Starting the step search at the top-left: both directions increase there, so you cannot decide which way to move.
  • Using the flattened search on a matrix that is only sorted by row and column: it is not one sorted sequence.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.