Search A 2D Matrix II Problem
Description
LeetCode Problem 240.
Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties:
- Integers in each row are sorted in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
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: 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 = 20
Output: false
Constraints:
- m == matrix.length
- n == matrix[i].length
- 1 <= n, m <= 300
- -10^9 <= matrix[i][j] <= 10^9
- All the integers in each row are sorted in ascending order.
- All the integers in each column are sorted in ascending order.
- -10^9 <= target <= 10^9
Solution
Approach: Search from the Top-Right Corner
Start at the top-right cell. Everything to its left in the same row is smaller, and everything below it in the same column is larger. So one comparison always rules out a whole row or a whole column:
- If the value equals
target, returntrue. - If the value is greater than
target, every cell below it in this column is also greater thantarget, so drop the column: move left. - If the value is smaller than
target, every cell to its left in this row is also smaller thantarget, so drop the row: move down.
Stop with false when we walk off the matrix (past the bottom or the left edge).
The corner matters: from the top-left, both moves (right and down) increase the value, so a comparison doesn't tell us which way to go. The bottom-left corner works too, with the directions flipped.
Complexity: O(m + n) time, where m and n are the number of rows and columns, since each step removes a row or a column. O(1) extra space.
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
# Start at the top-right corner: everything left of it is smaller, everything below it is larger.
row, col = 0, len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
value = matrix[row][col]
if value == target:
return True
if value > target:
col -= 1 # the whole column below is even larger
else:
row += 1 # the whole row to the left is even smaller
return False