Skip to content

Search a 2D Matrix

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix.

The matrix has these properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.
matrixtargetOutputExplanation
[[1,3,5,7],[10,11,16,20],[23,30,34,60]]3true3 is at index [0,1]
[[1,3,5,7],[10,11,16,20],[23,30,34,60]]13false13 doesn’t exist in matrix
[[1]]1trueSingle element, matches
[[1,3]]3true1D row search
  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -10^4 <= matrix[i][j], target <= 10^4
ApproachTimeSpaceNotes
Binary Search 2DO(log(m*n))O(1)Direct 2D indexing; most efficient
Flatten to 1DO(log(m*n))O(1)Treats matrix as 1D array; elegant conversion
Section titled “Approach 1: Binary Search (2D) (Recommended)”
★ Recommended

Recognize that the matrix is essentially a sorted 1D array arranged in 2D form. Use binary search on the flattened index space, converting 1D index to 2D using:

  • row = mid // n
  • col = mid % n

This is the most intuitive approach since it directly mimics 1D binary search.

⏱ Time O(log(m*n)) Binary search on flattened size 💾 Space O(1) Only pointers

Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3

Flattened: [1, 3, 5, 7, 10, 11, 16, 20, 23, 30, 34, 60] (conceptually)

IterationleftrightmidValueDecision
101151111 > 3; right = 4
204255 > 3; right = 1
301011 < 3; left = 1
41113Found!

2D Conversion: mid = 1 → row = 1 // 4 = 0, col = 1 % 4 = 1 → matrix[0][1] = 3 ✓

function searchMatrix(matrix, target):
m = len(matrix)
n = len(matrix[0])
left = 0
right = m * n - 1
while left <= right:
mid = (left + right) / 2
row = mid // n
col = mid % n
midValue = matrix[row][col]
if midValue == target:
return True
elif midValue < target:
left = mid + 1
else:
right = mid - 1
return False
search_2d_matrix_binary_search.py
from typing import List
def searchMatrix(matrix: List[List[int]], target: int) -> bool:
"""Binary search approach: O(log(m*n)) time, O(1) space"""
if not matrix or not matrix[0]:
return False
m, n = len(matrix), len(matrix[0])
left, right = 0, m * n - 1
while left <= right:
mid = (left + right) // 2
mid_value = matrix[mid // n][mid % n]
if mid_value == target:
return True
elif mid_value < target:
left = mid + 1
else:
right = mid - 1
return False
Section titled “Approach 2: Flatten (Conceptual 1D Binary Search)”
✓ Simple

Treat the 2D matrix as a flattened 1D array. The key insight: element at 1D index i corresponds to 2D position (i // n, i % n). Apply standard binary search on this virtual 1D array.

This approach emphasizes the mathematical transformation rather than the algorithm itself.

⏱ Time O(log(m*n)) Same as approach 1 💾 Space O(1) No extra structures

Input: matrix = [[1,3,5,7],[10,11,16,20]], target = 13

Virtual 1D Array Index Mapping:

Index: 0 1 2 3 4 5 6 7
Value: 1 3 5 7 10 11 16 20
Row: 0 0 0 0 1 1 1 1
Col: 0 1 2 3 0 1 2 3

Binary search on index space finds no match for 13.

function searchMatrix(matrix, target):
m = len(matrix)
n = len(matrix[0])
left = 0
right = m * n - 1
while left <= right:
mid = left + (right - left) / 2
row = mid // n
col = mid % n
value = matrix[row][col]
if value == target:
return True
elif value < target:
left = mid + 1
else:
right = mid - 1
return False
search_2d_matrix_flatten.py
from typing import List
def searchMatrix(matrix: List[List[int]], target: int) -> bool:
"""Flatten approach: O(log(m*n)) time, O(1) space"""
if not matrix or not matrix[0]:
return False
row_count = len(matrix)
col_count = len(matrix[0])
left, right = 0, row_count - 1
while left <= right:
mid_row = (left + right) // 2
if target < matrix[mid_row][0]:
right = mid_row - 1
elif target > matrix[mid_row][-1]:
left = mid_row + 1
else:
return target in matrix[mid_row]
return False
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
search_a_2d_matrix_space_optimized.py
"""
Solution for Search a 2D Matrix
"""
def solve():
"""Implementation for approach 3 of Search a 2D Matrix"""
pass
if __name__ == "__main__":
print("Solution ready")