Search a 2D Matrix

Search for a value in a row-sorted matrix.

Pattern

Binary Search on Matrix

This problem follows the Binary Search on Matrix pattern, commonly found in the Binary Search category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Treat the 2D matrix as a flattened sorted array. Binary search with index conversion.

Key Insight

The 2D-to-1D index mapping (mid // cols, mid % cols) lets you apply standard binary search without flattening the matrix.

Step-by-step

  1. 1Treat the 2D matrix as a flat sorted array of m*n elements
  2. 2Use binary search with index conversion: row = mid // cols, col = mid % cols
  3. 3Compare the element at (row, col) with the target
  4. 4Narrow the search range accordingly

Pseudocode

rows, cols = len(matrix), len(matrix[0])
left, right = 0, rows * cols - 1
while left <= right:
    mid = (left + right) // 2
    val = matrix[mid // cols][mid % cols]
    if val == target: return true
    elif val < target: left = mid + 1
    else: right = mid - 1
return false
Complexity Analysis

Time Complexity

O(log(m*n))

Space Complexity

O(1)
More Binary Search Problems

Master this pattern with YeetCode

Practice Search a 2D Matrix and similar Binary Search problems with flashcards. Build pattern recognition through active recall.

Practice this problem