Search a 2D Matrix (LeetCode 74): Solution and Explanation
You are given an m by n matrix where each row is sorted left to right and the first value of each row is larger than the last value of the row above. Decide whether a target value appears in the matrix, in logarithmic time.
Watch it run step by step
Try your own input and write the code →Intuition
Scanning every cell is O(m × n), and binary searching each row separately is O(m log n). Neither uses the second guarantee, that each row starts above where the previous row ended. Put those two facts together and the matrix, read row by row, is one long sorted list. If you wrote the rows end to end you would get a sorted array of m × n numbers, and searching a sorted array is the textbook binary search.
You do not need to build that flattened array. Any position k in the imaginary list maps back to a cell by simple arithmetic: with n columns, the row is k // n and the column is k % n. For example, in a matrix with four columns, position 5 is row 1, column 1. So you can run a standard binary search on the index range 0 to m × n - 1 and translate each midpoint into matrix coordinates only when you need to read the value.
This keeps every bit of the binary search reasoning from the one-dimensional problem: a closed range [l, r], a loop that runs while l <= r, and updates of mid + 1 or mid - 1 after each comparison. The cost is a single logarithm of the total number of cells.
Approach: Binary search on a virtual flattened array
- If the matrix is empty, return
False. Otherwise recordmrows andncolumns. - Set
l = 0andr = m * n - 1, the bounds of the imaginary flat array. - While
l <= r, computemid = (l + r) // 2. - Convert
midto coordinates and readmid_val = matrix[mid // n][mid % n]. - If
mid_valequals the target, returnTrue. If it is smaller, setl = mid + 1; if larger, setr = mid - 1. - When the range is empty, return
False.
Step-by-step example
matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 3
- m = 3, n = 4, so l = 0 and r = 11.
- mid = 5 maps to row 1, column 1, value 11. 11 > 3, so r = 4.
- mid = 2 maps to row 0, column 2, value 5. 5 > 3, so r = 1.
- mid = 0 maps to row 0, column 0, value 1. 1 < 3, so l = 1.
- mid = 1 maps to row 0, column 1, value 3, which equals the target. Return True.
Code: Python, Java, C++
1class Solution:
2 def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
3 if not matrix: return False
4 m, n = len(matrix), len(matrix[0])
5 l, r = 0, m * n - 1
6
7 while l <= r:
8 mid = (l + r) // 2
9 mid_val = matrix[mid // n][mid % n]
10
11 if mid_val == target:
12 return True
13 elif mid_val < target:
14 l = mid + 1
15 else:
16 r = mid - 1
17 return False1class Solution {
2 public boolean searchMatrix(int[][] matrix, int target) {
3 if (matrix.length == 0) return false;
4 int m = matrix.length, n = matrix[0].length;
5 int l = 0, r = m * n - 1;
6
7 while (l <= r) {
8 int mid = l + (r - l) / 2;
9 int midVal = matrix[mid / n][mid % n];
10
11 if (midVal == target) return true;
12 else if (midVal < target) l = mid + 1;
13 else r = mid - 1;
14 }
15 return false;
16 }
17}1class Solution {
2public:
3 bool searchMatrix(vector<vector<int>>& matrix, int target) {
4 if (matrix.empty()) return false;
5 int m = matrix.size(), n = matrix[0].size();
6 int l = 0, r = m * n - 1;
7
8 while (l <= r) {
9 int mid = l + (r - l) / 2;
10 int midVal = matrix[mid / n][mid % n];
11
12 if (midVal == target) return true;
13 else if (midVal < target) l = mid + 1;
14 else r = mid - 1;
15 }
16 return false;
17 }
18};Time and space complexity
O(log(m × n))
Binary search over m × n virtual positions halves the range each iteration, and the index conversion is constant time.
O(1)
The matrix is never copied or flattened; only a few integer indices are stored.
Other approaches
Two binary searches (time O(log m + log n), space O(1))
First binary search the first column (or row ranges) to find the only row that could contain the target, then binary search inside that row. Same total complexity, and it avoids the division and modulo arithmetic.
Staircase search from the top right (time O(m + n), space O(1))
Start at the top right corner and move left when the value is too big or down when too small. It works on weaker matrices where rows and columns are sorted independently, but here it is slower than binary search.
Common mistakes
- Converting the index with the number of rows instead of columns. The row is
mid // nand the column ismid % n, wherenis the row length. - Setting
r = m * ninstead ofm * n - 1. The upper bound must be the last valid position, or a read can go out of range. - Applying the staircase method and calling it logarithmic. Walking from a corner is O(m + n), which is fine for the variant where rows do not chain but misses the requirement here.
- Not handling an empty matrix or an empty first row before reading
matrix[0].
Frequently asked questions
How do you binary search a 2D matrix?
Treat the matrix as a sorted one-dimensional array of length m × n and binary search the index range. Convert each midpoint index to a row with mid // n and a column with mid % n.
What is the time complexity of Search a 2D Matrix?
O(log(m × n)), which equals O(log m + log n). Each step halves the number of candidate cells.
How is this different from Search a 2D Matrix II?
In the second version, rows and columns are sorted but a row does not have to start after the previous row ends, so the matrix is not one sorted list. That version is usually solved with the O(m + n) staircase walk.
Can I search the row first and then the column?
Yes. Binary search for the last row whose first element is at most the target, then binary search within that row. It has the same logarithmic complexity.