Searching a 2D Matrix
Problem Statement:
You are given an m x n integer matrix matrix with the following properties:
- Each row is sorted in non-decreasing order.
- The first integer of each row is greater than the last integer of the previous row.
Given an integer target, return true if target is in the matrix or false otherwise.
You must write a solution with a time complexity of O(log(m × n)).
Examples:
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 60]
]
target = 3
Output:
true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 60]
]
target = 13
Output:
false
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 100-10^4 <= matrix[i][j], target <= 10^4
Approach:
To achieve the required time complexity of O(log(m × n)), treat the matrix as a flattened sorted array and use binary search.
Key Observations:
- Matrix to 1D Mapping:
- Each element in the 2D matrix can be mapped to a 1D array index using:
- Row:
index // n - Column:
index % n
- Row:
- Each element in the 2D matrix can be mapped to a 1D array index using:
- Binary search can be performed directly on this virtual 1D array.
Implementation:
# Function to search the target in a 2D matrix
def searchMatrix(matrix, target):
# Edge case: empty matrix
if not matrix:
return False
# Dimensions of the matrix
m, n = len(matrix), len(matrix[0])
# Binary search boundaries
left, right = 0, m * n - 1
while left <= right:
mid = (left + right) // 2
# Convert mid index to 2D matrix coordinates
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
result = searchMatrix(matrix, target)
print(result) # Output: True
Explanation:
-
Initialization:
leftis set to0(start of the virtual array).rightis set tom × n - 1(end of the virtual array).
-
Binary Search:
- Calculate the middle index:
mid = (left + right) // 2. - Convert the middle index to matrix coordinates using:
- Row:
mid // n - Column:
mid % n
- Row:
- Compare
mid_value(element at matrix[row][col]) withtarget.- If equal, return
True. - If less, move
leftpointer tomid + 1. - If greater, move
rightpointer tomid - 1.
- If equal, return
- Calculate the middle index:
-
End Condition:
- If
left > right, the target is not in the matrix; returnFalse.
- If
Complexity Analysis:
- Time Complexity:
- Binary search runs in O(log(m × n)) because the virtual array has
m × nelements.
- Binary search runs in O(log(m × n)) because the virtual array has
- Space Complexity:
- O(1) since no additional space is used.
