150NeetCode 150

29.Search a 2D Matrix

MediumBinary Search · 2/7

Problem

You are given an m x n integer matrix with two properties:

  • Each row is sorted in non-decreasing order.
  • The first integer of each row is greater than the last integer of the previous row.

Given an integer target, return true if target is in the matrix and false otherwise. The solution must run in O(log(m · n)) time.

Examples

Input:  matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
Explanation: 3 is in row 0, column 1.
Input:  matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
Output: false
Explanation: 13 would belong in row 1 between 11 and 16, but it is not there.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -10^4 <= matrix[i][j], target <= 10^4

💡 Key Insight

The two properties together mean that reading the matrix row by row produces one fully sorted list of m · n numbers. So we can binary-search a "virtual" 1-D array of length m · n, translating a 1-D index k into the cell matrix[k / n][k % n]. No copying is needed.

Brute Force

TimeO(m · n)SpaceO(1).

Intuition

Scan every cell and compare it to target.

Algorithm

  1. For every row r and column c, if matrix[r][c] == target return true.
  2. Return false.

Visualization

target = 3
row 0: 1 ✗  3 ✓ → return true

Code

java
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        for (int[] row : matrix) {
            for (int value : row) {
                if (value == target) {
                    return true;
                }
            }
        }
        return false;
    }
}

Complexity

  • Time: O(m · n) — every cell may be visited.
  • Space: O(1).

Complexity Comparison

Approach Time Space
Brute Force O(m · n) O(1)
Staircase Search O(m + n) O(1)
Two Binary Searches O(log m + log n) O(1)
Flattened Binary Search O(log(m · n)) O(1)

Common Pitfalls

  • Mapping the index with the wrong dimension: it is mid / n and mid % n where n is the number of columns, not rows.
  • In the two-step approach, binary-searching only on row[0] and then picking the wrong row when target is smaller than every first element — check for "no row found".
  • Using the staircase method and claiming O(log) time — it is O(m + n); it is the right tool for LeetCode 240 (Search a 2D Matrix II) where rows do not chain together.
  • Forgetting the single-row / single-column case (m = 1 or n = 1) — the flattened search handles both naturally.