Search A 2D Matrix
To solve this coding challenge, we need to efficiently search for a target value in a 2D matrix that has distinct, sorted rows and columns. Since rows are sorted in non-decreasing order and the first integer of each row is greater than the last integer of the previous row, the matrix can be visualized as a single flattened, sorted array. This allows us to use binary search to achieve an O(log(m*n)) time complexity.
# Explanation:
- Matrix and Binary Search Setup :
- Each element in the matrix can be uniquely indexed using two coordinates, namely row and column indices.
- Since the matrix elements are sorted in a row-major order, it's feasible to map a 2D index to a 1D index, which is conducive to applying binary search.
- Defining Matrix Dimensions :
-
We determine the number of rows
m
n
- Binary Search Implementation :
-
Initialize two pointers
left
right
-
Calculate the middle index
mid
-
Compare the middle element with the target. If it matches, return
True
- Adjust the search range based on whether the middle element is less than or greater than the target.
-
If pointers cross without finding the element, return
False
- Matrix Initialization :
-
rows = len(matrix)
-
columns = len(matrix[0])
- Binary Search Initialization :
-
left = 0
-
right = (rows * columns) - 1
- Binary Search Loop :
-
Mid Calculation
:
mid = left + (right - left) // 2
- Mapping to 2D Coordinates :
-
row_index = mid // columns
-
column_index = mid % columns
-
mid_element = matrix[row_index][column_index]
- Comparison :
-
If
mid_element == target
True
-
If
mid_element < target
left
mid + 1
-
If
mid_element > target
right
mid - 1
- End Condition :
-
If the loop exits without finding the target, return
False
# Pseudocode with Comments:
# Given a matrix and a target value
# Initialize matrix dimensions
rows = number of rows in matrix
columns = number of columns in matrix
# Initialize search boundary pointers
left = 0
right = (rows * columns) - 1
# Conduct binary search
while left <= right:
# Calculate the middle index
mid = left + (right - left) // 2
# Map mid index back to 2D coordinates
row_index = mid // columns
column_index = mid % columns
mid_element = matrix[row_index][column_index]
# Compare the middle element with the target value
if mid_element == target:
return True # Target found
elif mid_element < target:
left = mid + 1 # Adjust the search to the right half
else:
right = mid - 1 # Adjust the search to the left half
# Target is not found in the matrix
return False