Searching a sorted matrix
28 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Interviewers love asking "Search a sorted 2D matrix" because the phrase "sorted matrix" actually describes two different matrix structures! Knowing how to distinguish them—and applying virtual 1D binary search (O(log(R · C))) to the first and corner staircase search (O(R + C)) to the second—turns both into 10-line solutions.
Treating the matrix as one flat array
In Search a 2D Matrix I, an R × C matrix has two properties:
- Each row is sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example 1 · Brute force: check every cell (O(R · C) time, O(1) space)
public class MatrixScanAll { public static void main(String[] args) { int size = 100; int[][] matrix = new int[size][size]; for (int r = 0; r < size; r++) { for (int c = 0; c < size; c++) { matrix[r][c] = r * size + c; } } int target = 9999; int checks = 0; boolean found = false; for (int r = 0; r < size && !found; r++) { for (int c = 0; c < size && !found; c++) { checks++; if (matrix[r][c] == target) found = true; } } System.out.println("Found: " + found + " after " + checks + " checks"); }}Found: true after 10000 checks
What this code does
- On a 100 × 100 matrix, looking for the last value takes 10,000 checks.
- It is slow because it ignores that every row and every column is sorted.
Example 2 · Better: find the row, then binary search it (O(R + log C) time, O(1) space)
public class MatrixRowThenSearch { public static void main(String[] args) { int size = 100; int[][] matrix = new int[size][size]; for (int r = 0; r < size; r++) { for (int c = 0; c < size; c++) { matrix[r][c] = r * size + c; } } int target = 9999; int checks = 0; int row = 0; while (row < size - 1) { checks++; if (matrix[row][size - 1] >= target) break; row++; } int lo = 0, hi = size - 1; boolean found = false; while (lo <= hi) { int mid = lo + (hi - lo) / 2; checks++; if (matrix[row][mid] == target) { found = true; break; } else if (matrix[row][mid] < target) { lo = mid + 1; } else { hi = mid - 1; } } System.out.println("Found: " + found + " after " + checks + " checks"); }}Found: true after 106 checks
What this code does
- Checking row ends finds the row in 99 checks, then binary search needs 7 more: 106 checks instead of 10,000.
- It is still slow because the row is found one row at a time, even though the rows continue each other in order.
Example 3 · Optimal: binary search the whole matrix as one flat array (O(log(R · C)) time, O(1) space)
public class SearchMatrixFlatDemo { public static boolean searchMatrix(int[][] matrix, int target) { int R = matrix.length, C = matrix[0].length; int lo = 0, hi = R * C - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; int val = matrix[mid / C][mid % C]; if (val == target) return true; if (val < target) lo = mid + 1; else hi = mid - 1; } return false; }
public static void main(String[] args) { int[][] mat = { {1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60} }; System.out.println("Search 16: " + searchMatrix(mat, 16)); System.out.println("Search 13: " + searchMatrix(mat, 13)); }}Search 16: true Search 13: false
What this code does
- The 3x4 matrix is treated as indices 0..11; index mid = 6 maps to row 6 / 4 = 1, col 6 % 4 = 2 (value 16).
- Only at most 4 comparisons are needed to search all 12 cells.
- Each row continues where the previous one ended, so one binary search over 10,000 cells needs only 14 checks (about log₂ 10,000).
int row = mid / C;(how many full rows of widthCcome beforemid)int col = mid % C;(the offset within that row)- Time complexity: O(log(R · C)) = O(log R + log C), space complexity: O(1).
If you read this matrix row by row from top-left (0, 0) to bottom-right (R - 1, C - 1), all R · C numbers form one single globally sorted 1D array of length R · C! You do not need to allocate a new 1D array (which would waste O(R · C) time and space). Instead, run classic binary search on the virtual 1D index mid in [0 .. R * C - 1], and convert mid to 2D coordinates (row, col) on the fly:
C (the number of columns matrix[0].length), NEVER by R!Staircase search from a corner
In Search a 2D Matrix II, each row and each column is sorted, but a row can end higher than the next row starts (row 0 ends at 11, row 1 starts at 2), so the matrix is not one sorted list.
- Start at
r = 0, c = C - 1(top-right corner). - While
r < R && c >= 0: comparemat[r][c]withtarget. - If
mat[r][c] == target, returntrue. - If
mat[r][c] > target, every cell below in columncis even larger, so eliminate columnc(c--). - If
mat[r][c] < target, every cell to the left in rowris even smaller, so eliminate rowr(r++).
Example 4 · Staircase search from the top-right corner
import java.util.Arrays;
public class StaircaseSearchDemo { public static int[] searchMatrixII(int[][] mat, int target) { int R = mat.length, C = mat[0].length; int r = 0, c = C - 1; // top-right corner while (r < R && c >= 0) { if (mat[r][c] == target) { return new int[]{r, c}; } else if (mat[r][c] > target) { c--; // eliminate column c } else { r++; // eliminate row r } } return new int[]{-1, -1}; }
public static void main(String[] args) { int[][] mat = { {1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24} }; System.out.println("Find 14: " + Arrays.toString(searchMatrixII(mat, 14))); System.out.println("Find 20: " + Arrays.toString(searchMatrixII(mat, 20))); }}Find 14: [3, 2] Find 20: [-1, -1]
What this code does
- Starting at (0, 4) = 15: 15 > 14 -> c=3 (11); 11 < 14 -> r=1 (12); 12 < 14 -> r=2 (16); 16 > 14 -> c=2 (9); 9 < 14 -> r=3 (14) -> found at [3, 2]!
- Because each step either increments r or decrements c, the loop runs at most R + C times.
Example 5 · Counting negative numbers in a row-and-column sorted matrix in O(R + C)
public class CountNegativesMatrixDemo { public static int countNegatives(int[][] grid) { int R = grid.length, C = grid[0].length; int r = R - 1, c = 0; // bottom-left corner (grid is sorted non-increasing) int count = 0; while (r >= 0 && c < C) { if (grid[r][c] < 0) { // Since row r is non-increasing, grid[r][c .. C-1] are ALL negative! count += (C - c); r--; } else { c++; } } return count; }
public static void main(String[] args) { int[][] grid = { { 4, 3, 2, -1}, { 3, 2, 1, -1}, { 1, 1, -1, -2}, {-1, -1, -2, -3} }; System.out.println("Negative count: " + countNegatives(grid)); }}Negative count: 8
What this code does
- The staircase boundary between non-negative and negative numbers climbs from bottom-left to top-right.
- Whenever grid[r][c] < 0, all C - c cells to its right in row r are also negative, so we add C - c in O(1) and step up to row r - 1.
Why can't you start at the top-left (0, 0)? Because moving right increases the value AND moving down increases the value—if target > mat[0][0], you don't know which way to go! Now start at the top-right corner (r = 0, c = C - 1) (here 11). Every element below (r, c) in column c is larger (>= mat[r][c]), and every element to the left of (r, c) in row r is smaller (<= mat[r][c]). So every comparison at (r, c) eliminates either the entire current row or the entire current column:
Choosing between the two
How do you choose between virtual 1D binary search, row-by-row binary search, and staircase search?
Compare the matrix guarantee and dimensions R × C:
- Row-major globally sorted (
mat[r][0] > mat[r - 1][C - 1]): use virtual 1D binary search in O(log(R · C)) time. - Row-and-column sorted (
RandCsimilar size): use top-right (or bottom-left) staircase search in O(R + C) time. - Row-and-column sorted where R is tiny and C is huge (e.g., R = 3, C = 1,000,000): binary searching each of the R rows takes O(R log C) time (≈ 3 × 20 = 60 steps), which beats O(R + C) staircase search (1,000,003 steps)!
Next step
Check your understanding
10 quick questions