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 - Problem OverviewInput Matrix (sorted):147112581236916Target: 5Start from top-right (11)11 > 5, move left to 77 > 5, move left to 44 < 5, move down to 5Output: trueTime: O(m+n), Space: O(1)Eliminate row or column at each step!
Understanding the Visualization
1
Input
Sorted matrix and target value to find
2
Strategy
Start from top-right, eliminate row or column
3
Output
Return true if target found, false otherwise
Key Takeaway
🎯 Key Insight: Start from top-right corner to eliminate either a row or column at each comparison step
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