The problem statement involves searching for a given integer (target
) within an m x n
integer matrix that adheres to two key properties:
The objective is to determine whether the target
integer exists within the matrix and to return true
if it does and false
otherwise. The solution must achieve this in $O(log(m \times n))$ time complexity.
Solution:
To solve this problem within the required time complexity $O(log(m \times n))$, we can use a binary search
approach. Since the matrix’s rows are sorted and the first integer of each row is greater than the last integer of the previous row, we can treat the matrix as a flattened sorted list and apply binary search on it.
Here is how to do it:
m x n - 1
Find the middle index between left and the right pointers.
Calculate the corresponding rows and column in the matrix for the middle index:
# Can either do this
row, col = divmod(mid, n)
print(matrix[row][col]) #print the middle value in the matrix
# Or this
mid_value = matrix[mid // n][mid % n]
Compare the target with the element at the calculated row and column.
If the target found, return true.
If the target is less than the element, move the right pointer to the middle - 1
index.
If the target is greater than the element, move the left pointer to the middle + 1
index.
Implementation:
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 target == mid_value:
return True
elif target < mid_value:
right = mid - 1
else:
left = mid + 1
return False
Another problem statement could be to search a given target
value within m x n
integer matrix. The matrix is structured such that all row’s integers are sorted in ascending order from left to right, and all column’s integers are sorted in ascending order from top to bottom. The goal is to determine whether the target
value exists in the matrix, returning true
if so, and false
otherwise.
A good approach is to start from the top-right corner of the matrix. The algorithm proceeds as follows:
(row, col)