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 INPUT 4x4 Matrix (sorted rows) 1 4 7 11 2 5 8 12 3 6 9 16 10 13 14 17 Target Value target = 5 m = 4 rows, n = 4 cols Total: 16 elements Rows sorted, first elem > prev last ALGORITHM STEPS 1 Binary Search Row Find row where target could exist (first col) 2 Compare First Column 5 > 2 (row 1 first) 5 < 3 (row 2 first) 3 Select Row 1 Row contains [2,5,8,12] 2 <= 5 <= 12 (valid) 4 Binary Search Column Search in row 1: mid=1, arr[1]=5, FOUND! Row 1 Search 2 5 8 12 mid index = (0+3)/2 = 1 matrix[1][1] = 5 = target FINAL RESULT true Target Found! Location Found Row: 1, Column: 1 matrix[1][1] = 5 5 == 5 (match!) Time Complexity O(log m + log n) = O(log(m*n)) satisfied Output: true Key Insight: The "Search Row Then Column" approach uses two binary searches: first to find the candidate row where target could exist (by comparing first elements), then to search within that row. This achieves O(log m) + O(log n) = O(log(m*n)) time complexity as required. TutorialsPoint - Search a 2D Matrix | Search Row Then Column Approach
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