Search in 2D matrix II
Here are the detailed commercial-grade notes for the problem Search a 2D Matrix II from LeetCode:
Problem Link
Problem Statement
Given an m x n matrix of integers where:
-
Each row is sorted in ascending order from left to right.
-
Each column is sorted in ascending order from top to bottom.
Implement an efficient algorithm that searches for a target value in this matrix. Return true if the target exists, otherwise return false.
Examples
Example 1:
Input:
matrix = [[1,4,7,11,15],
[2,5,8,12,19],
[3,6,9,16,22],
[10,13,14,17,24],
[18,21,23,26,30]]
target = 5
Output: true
Example 2:
Input:
Same matrix, target = 20
Output: false
Constraints
-
m == matrix.length -
n == matrix[i].length -
1 <= n, m <= 300 -
-10⁹ <= matrix[i][j], target <= 10⁹ -
All integers in rows and columns are individually sorted in ascending order.
Intuition
We are given a matrix where both rows and columns are sorted, which rules out a simple binary search over the entire matrix directly. But it gives us a strong clue:
-
If we start from the top-right corner:
-
If current element > target → eliminate the column
-
If current element < target → eliminate the row
-
This two-pointer technique uses the sorted structure of the matrix to eliminate one row or one column in each step, ensuring O(m + n) time complexity.
Approach
-
Start from the top-right corner:
row = 0,col = n - 1 -
Loop until you go out of matrix bounds:
-
If
matrix[row][col] == target: returntrue -
If
matrix[row][col] > target: move left →col-- -
Else: move down →
row++
-
-
If loop ends, return
false
Java Code
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int row = 0, col = n - 1;
while (row < m && col >= 0) {
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] > target) {
col--;
} else {
row++;
}
}
return false;
}
}
Time and Space Complexity
-
Time Complexity:
O(m + n)
In the worst case, we move from top-right to bottom-left throughmrows andncolumns. -
Space Complexity:
O(1)
No extra space is used.
Dry Run
Input:
matrix = [[1,4,7,11,15],
[2,5,8,12,19],
[3,6,9,16,22],
[10,13,14,17,24],
[18,21,23,26,30]]
target = 5
Steps:
-
Start at (0,4) → 15 → 15 > 5 → move left
-
(0,3) → 11 → 11 > 5 → move left
-
(0,2) → 7 → 7 > 5 → move left
-
(0,1) → 4 → 4 < 5 → move down
-
(1,1) → 5 → match → return
true
Conclusion
This problem is a classic application of 2D matrix traversal using logical elimination, leveraging sorted properties of both rows and columns. Instead of brute force or nested binary searches, this O(m + n) solution is clean, intuitive, and efficient.
Whenever you're faced with a matrix sorted both row-wise and column-wise, consider starting from a corner (typically top-right or bottom-left) to apply this traversal technique.