Search a 2D Matrix II - Problem
Imagine you have a cleverly organized library where books are arranged in a special way: each row is sorted by publication year (left to right), and each column is sorted by page count (top to bottom). Now you need to find a specific book efficiently!
Given an m x n integer matrix with the following properties:
- Row-wise sorted: Integers in each row are in ascending order from left to right
- Column-wise sorted: Integers in each column are in ascending order from top to bottom
Write an efficient algorithm to search for a target value. Return true if found, false otherwise.
Key Challenge: The matrix is partially sorted - it's not a simple 1D sorted array, but has structure we can exploit!
Input & Output
example_1.py โ Standard Search
$
Input:
matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16]], target = 5
โบ
Output:
true
๐ก Note:
The target 5 exists in the matrix at position [1,1]. Using the optimal approach, we start from top-right (11), move left to 7, then down to 12, left to 8, down to 16, left to 9, down (out of bounds), left to 6, down (out of bounds), left to 3, down (out of bounds), left to 2, down to 5 - found!
example_2.py โ Target Not Found
$
Input:
matrix = [[1,4,7,11],[2,5,8,12],[3,6,9,16]], target = 13
โบ
Output:
false
๐ก Note:
The target 13 does not exist in the matrix. Starting from top-right (11), we move down to 12, down to 16. Since 16 > 13, we move left to 9, but 9 < 13, so we move down (out of bounds). Search space exhausted without finding 13.
example_3.py โ Single Element Matrix
$
Input:
matrix = [[5]], target = 5
โบ
Output:
true
๐ก Note:
Edge case with a single element matrix. The target 5 matches the only element in the matrix at position [0,0].
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 โค m, n โค 300
- -109 โค matrix[i][j] โค 109
- Each row is sorted in non-decreasing order
- Each column is sorted in non-decreasing order
- -109 โค target โค 109
Visualization
Tap to expand
Understanding the Visualization
1
Start Position
Begin at top-right corner - this position gives you maximum information
2
Smart Decision
If current > target, move left (eliminate column). If current < target, move down (eliminate row)
3
Eliminate Search Space
Each move eliminates an entire row or column, reducing search space efficiently
4
Find or Exhaust
Continue until target is found or search boundaries are exceeded
Key Takeaway
๐ฏ Key Insight: Starting from the top-right corner allows us to make optimal decisions at each step, eliminating entire rows or columns and achieving linear time complexity!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code