Search a 2D Matrix II - Problem

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

• Integers in each row are sorted in ascending order from left to right.
• Integers in each column are sorted in ascending order from top to bottom.

Return true if target is found, otherwise return false.

Input & Output

Example 1 — Basic Search
$ Input: matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16]], target = 5
Output: true
💡 Note: Target 5 exists in the matrix at position (1,1). Using the optimal approach: start at top-right (11), 11 > 5 so move left to 7, 7 > 5 so move left to 4, 4 < 5 so move down to 5, found!
Example 2 — Target Not Found
$ Input: matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16]], target = 13
Output: false
💡 Note: Target 13 does not exist in the matrix. Starting from top-right, we would traverse through several cells but never find 13, eventually going out of bounds.
Example 3 — Single Element
$ Input: matrix = [[5]], target = 5
Output: true
💡 Note: Edge case with single element matrix. The target 5 matches the only element in the matrix.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ n, m ≤ 300
  • -109 ≤ matrix[i][j] ≤ 109
  • All the integers in each row are sorted in ascending order.
  • All the integers in each column are sorted in ascending order.
  • -109 ≤ target ≤ 109

Visualization

Tap to expand
Search a 2D Matrix II INPUT 2D Matrix (sorted rows & cols) 1 4 7 11 2 5 8 12 3 6 9 16 Rows: sorted left-->right Cols: sorted top-->bottom Target Value 5 Start: Top-Right Corner Start ALGORITHM STEPS 1 Start Top-Right row=0, col=3 (val=11) 2 Compare & Move 11>5: move left (col--) 3 Continue Search 7>5: left, 4<5: down 4 Found Target row=1, col=1: 5==5 Search Path: Red=visited, Green=found FINAL RESULT Target Found! true Position Found matrix[1][1] = 5 Row: 1, Column: 1 Time Complexity O(m + n) Linear in matrix dimensions Output: true Key Insight: Starting from top-right corner, we can eliminate one row OR one column with each comparison. If current value > target: move left (eliminate column). If current value < target: move down (eliminate row). TutorialsPoint - Search a 2D Matrix II | Search Space Reduction Approach
Asked in
Google 42 Amazon 38 Microsoft 28 Apple 22
125.0K Views
High Frequency
~15 min Avg. Time
2.8K 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