Search a 2D Matrix II (LeetCode 240): Solution and Explanation
You are given a matrix where every row is sorted left to right and every column is sorted top to bottom. Decide whether a target value appears anywhere in it.
Watch it run step by step
Try your own input and write the code →Intuition
Checking every cell works in O(m × n) and ignores the sorting entirely. A step better is to binary search each row, which costs O(m log n). That uses the row order but still ignores the column order, and unlike the first version of this problem, rows do not continue from one another, so you cannot treat the matrix as one long sorted array.
The insight is to start at a corner where the two sort orders point in opposite directions. At the top-right corner, moving left makes values smaller and moving down makes values larger. That gives every comparison a clear meaning. If the current value is larger than the target, nothing below it in this column can be the target, because the column only gets larger, so you can discard the entire column and move left. If the current value is smaller, nothing to its left in this row can match, since the row only gets smaller going left, so you discard the entire row and move down.
Each comparison removes a full row or a full column, and there are only m rows and n columns to remove. So the search finishes in at most m + n steps, either by finding the target or by walking off the matrix.
The bottom-left corner works just as well, with the directions swapped. The top-left and bottom-right corners do not, because from there both neighbors move in the same direction and a comparison does not tell you which way to go.
Approach: Staircase search from the top-right
- If the matrix is empty, return false.
- Start at row
r = 0and columnc = len(matrix[0]) - 1, the top-right corner. - While
ris a valid row andc >= 0, comparematrix[r][c]with the target. - If they are equal, return true.
- If the value is larger than the target, move left with
c -= 1, eliminating the column. - If it is smaller, move down with
r += 1, eliminating the row. If the loop exits, return false.
Step-by-step example
matrix = [[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]], target = 5
- Start at (0, 4), value 15. It is larger than 5, so move left to column 3.
- Value 11 is larger than 5, move left. Value 7 at (0, 2) is larger, move left again.
- Value 4 at (0, 1) is smaller than 5, so the rest of row 0 to the left is too small. Move down to (1, 1).
- Value 5 at (1, 1) equals the target, so the function returns true after five comparisons.
Code: Python, Java, C++
1class Solution:
2 def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
3 if not matrix: return False
4 r, c = 0, len(matrix[0]) - 1
5
6 while r < len(matrix) and c >= 0:
7 if matrix[r][c] == target:
8 return True
9 elif matrix[r][c] > target:
10 c -= 1
11 else:
12 r += 1
13 return False1class Solution {
2 public boolean searchMatrix(int[][] matrix, int target) {
3 if (matrix == null || matrix.length == 0) return false;
4 int r = 0, c = matrix[0].length - 1;
5
6 while (r < matrix.length && c >= 0) {
7 if (matrix[r][c] == target) return true;
8 else if (matrix[r][c] > target) c--;
9 else r++;
10 }
11 return false;
12 }
13}1class Solution {
2public:
3 bool searchMatrix(vector<vector<int>>& matrix, int target) {
4 if (matrix.empty()) return false;
5 int r = 0, c = matrix[0].size() - 1;
6
7 while (r < matrix.size() && c >= 0) {
8 if (matrix[r][c] == target) return true;
9 else if (matrix[r][c] > target) c--;
10 else r++;
11 }
12 return false;
13 }
14};Time and space complexity
O(m + n)
Every step either decreases the column index or increases the row index, so there are at most m + n steps before one of them leaves the matrix.
O(1)
Only the two indices are stored.
Other approaches
Binary search each row (time O(m log n), space O(1))
Run a standard binary search on every row. It only uses the row ordering, but it is easy to write and beats the staircase when the matrix is very wide and short.
Divide and conquer on quadrants (time O((m × n)^0.79), space O(log(m × n)))
Compare the target with the center element and discard one of the four quadrants, recursing into the other three. It is a nice exercise in using both orders, but it is more complex and no faster than the staircase in practice.
Common mistakes
- Starting at the top-left corner, where both moves increase the value and a comparison gives no direction.
- Treating the matrix as one flattened sorted array. That works for the first version of the problem but not here, because a row's last value can be larger than the next row's first value.
- Checking
c < len(matrix[0])instead ofc >= 0in the loop condition when starting at the right edge. - Indexing
matrix[0]before checking that the matrix has at least one row.
Frequently asked questions
What is the difference between Search a 2D Matrix and Search a 2D Matrix II?
In the first problem each row starts after the previous row ends, so the whole matrix is one sorted sequence and a single binary search works. Here rows and columns are sorted independently, so the staircase search is the standard approach.
Why start from the top-right corner?
From that corner, moving left decreases the value and moving down increases it. Each comparison therefore tells you exactly which direction to move and lets you discard a whole row or column.
What is the time complexity of the staircase search?
It is O(m + n). Each step removes one row or one column, and there are only m + n of them in total.
Is binary search on each row faster?
Row-wise binary search is O(m log n), which is better only when the matrix has few rows and many columns. For square matrices the staircase is faster.