Search a 2D Matrix (LeetCode 74): Solution and Explanation

Medium
Array
Binary Search
Matrix

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. If the matrix is empty, return False. Otherwise record m rows and n columns.
  2. Set l = 0 and r = m * n - 1, the bounds of the imaginary flat array.
  3. While l <= r, compute mid = (l + r) // 2.
  4. Convert mid to coordinates and read mid_val = matrix[mid // n][mid % n].
  5. If mid_val equals the target, return True. If it is smaller, set l = mid + 1; if larger, set r = mid - 1.
  6. 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
  1. m = 3, n = 4, so l = 0 and r = 11.
  2. mid = 5 maps to row 1, column 1, value 11. 11 > 3, so r = 4.
  3. mid = 2 maps to row 0, column 2, value 5. 5 > 3, so r = 1.
  4. mid = 0 maps to row 0, column 0, value 1. 1 < 3, so l = 1.
  5. 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 False

Time and space complexity

Time

O(log(m × n))

Binary search over m × n virtual positions halves the range each iteration, and the index conversion is constant time.

Space

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 // n and the column is mid % n, where n is the row length.
  • Setting r = m * n instead of m * 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.