Search a 2D Matrix II
Difficulty: Medium · Pattern: Binary Search · LeetCode #240
Each row is sorted left to right and each column top to bottom (rows don't continue each other). Return whether target exists.
Examples
text
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 → true
target = 20 → falseHints
- Start at the top-right corner. What does comparing that value with the target tell you?
Approach
At the top-right cell, the value is the largest in its row and the smallest in its column. If it's greater than the target, the whole column is too big, so move left; if it's smaller, the whole row is too small, so move down. Each step eliminates a row or column: O(m + n).
Complexity
Time: O(m + n). Space: O(1).
Python solution
def searchMatrix(matrix, target):
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 FalseJavaScript solution
function searchMatrix(matrix, target) {
let r = 0, c = matrix[0].length - 1;
while (r < matrix.length && c >= 0) { const v = matrix[r][c]; if (v === target) return true; if (v > target) c--; else r++; }
return false;
}