Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:
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.lengthn == matrix[i].length1 <= n, m <= 300-109 <= matrix[i][j] <= 109-109 <= target <= 109When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are looking for a specific hidden item in a grid filled with many items. The brute force approach simply means checking every single spot in the grid one by one until you either find what you are looking for or run out of spots.
Here's how the algorithm would work step-by-step:
def search_matrix(matrix, target): # Ensure the matrix is not empty to prevent out of bounds errors during traversal if not matrix or not matrix[0]: return False row_count = len(matrix) column_count = len(matrix[0]) # Iterate through every row and column combination to inspect all elements for row_index in range(row_count): for column_index in range(column_count): current_element = matrix[row_index][column_index] # Compare current grid element with target to determine if it is a match if current_element == target: return True # Complete the search over all spots before concluding the target is absent return FalseInstead of searching every single number in the grid, the optimal approach starts at a clever corner where we can eliminate a whole row or column with a single comparison. By strategically moving away from that corner based on what we see, we quickly zero in on our target.
Here's how the algorithm would work step-by-step:
class Solution:
def search_matrix(self, matrix: list[list[int]], target_value: int) -> bool:
if not matrix or not matrix[0]:
return False
row_index = 0
column_index = len(matrix[0]) - 1
while row_index < len(matrix) and column_index >= 0:
current_element = matrix[row_index][column_index]
# Exact match found means we can terminate early and return true.
if current_element == target_value:
return True
# Element is too large, eliminate current column by moving left.
elif current_element > target_value:
column_index -= 1
# Element is too small, eliminate current row by moving down.
else:
row_index += 1
# Stepping off the grid bounds confirms the target does not exist.
return False| Case | How to Handle |
|---|---|
| Empty matrix or null matrix input | Check if the matrix is null or has zero rows or columns and return false immediately. |
| Matrix with dimensions 1x1 | The search pointer starts at the single element and correctly compares it to the target. |
| Target is smaller than the smallest element or larger than the largest element | The search bounds will step out of the matrix dimensions, safely terminating with a false return value. |
| Target is located at the extreme corners of the matrix | The top-right or bottom-left starting strategy ensures these boundary positions are evaluated efficiently. |
| Matrix containing negative numbers, zeros, and positive numbers | The sorted order properties hold regardless of sign, so relative comparisons remain mathematically valid. |
| Matrix with all identical values | The directional search logic will consistently move in one direction until it matches or exhausts bounds. |
| Maximum-sized inputs near memory or time constraints | The linear time complexity approach avoids extra space and easily processes large matrices within limits. |
| Target exists multiple times within the matrix | The boolean search requirement means returning true upon the first encountered match is sufficient. |