Search a 2D Matrix - Problem

You are given an m x n integer matrix matrix with the following 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 matrix or false otherwise.

You must write a solution in O(log(m * n)) time complexity.

Input & Output

Example 1 — Basic Search
$ Input: matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 5
Output: true
💡 Note: The target 5 exists in the matrix at position [1,1]. The matrix satisfies both properties: rows are sorted and first element of each row is greater than last element of previous row.
Example 2 — Target Not Found
$ Input: matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 13
Output: true
💡 Note: The target 13 exists in the matrix at position [3,1]. Even though it's in the last row, binary search efficiently finds it in O(log(m*n)) time.
Example 3 — Target Not Present
$ Input: matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16],[10,13,14,17]], target = 15
Output: false
💡 Note: The target 15 does not exist anywhere in the matrix. Binary search efficiently determines this without checking all elements.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 100
  • -104 ≤ matrix[i][j], target ≤ 104

Visualization

Tap to expand
Search a 2D Matrix: Binary Search ApproachInput Matrix:1475812Target: 5Properties:• Rows sorted• First > Last of prev rowProcess:1. Treat as 1D array: [1,4,7,5,8,12]2. Binary search: mid=2 → matrix[2/3][2%3] = matrix[0][2] = 73. 7>5, search left half → find 5 at index 3 → matrix[1][0]Result: true
Understanding the Visualization
1
Input
Sorted matrix with special properties + target value
2
Process
Use binary search treating matrix as 1D array
3
Output
Return true if target found, false otherwise
Key Takeaway
🎯 Key Insight: A sorted matrix with special properties can be searched like a single sorted array using coordinate transformation
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 25
67.5K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen