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.length
n == matrix[i].length
1 <= n, m <= 300
-109 <= matrix[i][j] <= 109
-109 <= target <= 109
This problem asks to efficiently search for a target value within an m x n matrix where each row and column is sorted in ascending order. Two efficient approaches are presented: Binary Search and a linear search starting from a corner.
This approach iterates through each row of the matrix and performs a binary search on that row to check if the target exists.
Algorithm:
bisect_left
in Python, Arrays.binarySearch
in Java, lower_bound
in C++, sort.SearchInts
in Go, _.sortedIndex
in TypeScript/JavaScript) is performed to find the index of the first element greater than or equal to the target. If the target is found, the function immediately returns true
.false
.Time Complexity: O(m * log n), where 'm' is the number of rows and 'n' is the number of columns. This is because we perform a binary search (O(log n)) on each of the 'm' rows.
Space Complexity: O(1). The algorithm uses constant extra space.
This approach uses a more optimized linear search strategy. It starts from either the bottom-left or top-right corner of the matrix and strategically moves based on comparisons with the target.
Algorithm (using Bottom-Left):
i = m - 1
, j = 0
).matrix[i][j]
with the target:
matrix[i][j] == target
, return true
.matrix[i][j] > target
, move upwards (decrement i
) because all elements to the right in the current row are larger.matrix[i][j] < target
, move rightwards (increment j
) because all elements above in the current column are smaller.false
.Time Complexity: O(m + n). In the worst case, the algorithm traverses at most all the rows and columns once.
Space Complexity: O(1). Constant extra space is used.
Code Examples (Python):
Solution 1 (Binary Search):
import bisect
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
for row in matrix:
j = bisect.bisect_left(row, target)
if j < len(matrix[0]) and row[j] == target:
return True
return False
Solution 2 (Bottom-Left Search):
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m, n = len(matrix), len(matrix[0])
i, j = m - 1, 0
while i >= 0 and j < n:
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
i -= 1
else:
j += 1
return False
The code examples in other languages follow similar logic, adapting the specific binary search and array/matrix access methods for their respective languages. Solution 2 is generally preferred due to its superior time complexity in most cases.