240. Search a 2D Matrix II
Asked at 13Apple55Amazon50Microsoft44Bloomberg43Google42Meta39Goldman Sachs36Zomato62ServiceNow55Oracle45PayPal42tcs27TikTok26
Problem
In the m×n matrix, every row is sorted left to right and every column is sorted top to bottom. Decide whether target is in it.
Example: [[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 → true, target = 20 → false
Constraints: up to 300 × 300.
Rows and columns sorted (but rows don't continue each other). Start at the top-right: if bigger than target move left (the whole column below is bigger too), if smaller move down.
1 4 7 [11] 15 target 5: 11 > 5 <-, 7 > 5 <-, 4 < 5 v, 5 found
2 5 8 12 19
3 6 9 16 22
Complexity: O(m + n).
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
r, c = 0, len(matrix[0]) - 1
while r < len(matrix) and c >= 0:
v = matrix[r][c]
if v == target:
return True
if v > target:
c -= 1
else:
r += 1
return False
M = [[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]]
assert Solution().searchMatrix(M, 5) is True
assert Solution().searchMatrix(M, 20) is False
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int r = 0, c = matrix[0].length - 1;
while (r < matrix.length && c >= 0) {
if (matrix[r][c] == target) return true;
if (matrix[r][c] > target) c--; else r++;
}
return false;
}
}
func searchMatrix(matrix [][]int, target int) bool {
r, c := 0, len(matrix[0])-1 // start top-right: left is smaller, down is bigger
for r < len(matrix) && c >= 0 {
v := matrix[r][c]
switch {
case v == target:
return true
case v > target:
c--
default:
r++
}
}
return false
}