Skip to content

Add search 2D matrix algorithm #2695

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions algorithms/search/search_2D_matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""
Given an m x n matrix where each row is sorted in ascending order,
and the first element of each row is greater than the last element of the previous row,
search for a target value efficiently.

For Example:
Input: matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 60]
],
target = 3
Output: True
"""
from typing import List
def searchMatrix(matrix, target):
# Edge case: if matrix is empty or has no columns
if not matrix or not matrix[0]:
return False

m = len(matrix) # Number of rows
n = len(matrix[0]) # Number of columns

left = 0
right = m * n - 1 # Treat matrix as a flattened array of size m * n

# Binary search over the flattened 1D view
while left <= right:
mid = (left + right) // 2

# Map mid index to matrix coordinates
row = mid // n
col = mid % n
current_element = matrix[row][col]

if current_element == target:
return True # Target found
elif current_element < target:
left = mid + 1 # Move right
else:
right = mid - 1 # Move left

return False # Target not found