Write an efficient algorithm to search for a value in an m x n
matrix. This matrix has the following properties:
Given a matrix
and a target
value, return true if the target
is found in the matrix, and false otherwise.
Input: matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 60]
], target = 3
Output: true
Input: matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 60]
], target = 13
Output: false
Given the properties of the matrix, it can be viewed as a sorted 1D array. We can thus use binary search to efficiently search for the target. The general strategy is as follows:
m * n
.True
.False
.def searchMatrix(matrix, target):
if not matrix or not matrix[0]:
return False
m, n = len(matrix), len(matrix[0])
left, right = 0, m * n - 1
while left <= right:
mid = (left + right) // 2
mid_value = matrix[mid // n][mid % n]
if mid_value == target:
return True
elif mid_value < target:
left = mid + 1
else:
right = mid - 1
return False
# Example usage:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 60]
]
target = 3
print(searchMatrix(matrix, target)) # Output: True
target = 13
print(searchMatrix(matrix, target)) # Output: False
The time complexity of the solution is O(log(m * n))
where m
is the number of rows and n
is the number of columns. This is because we are performing a binary search on m * n
elements.
This approach ensures that the search is efficient even for large matrices.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?