Skip to content

Commit

Permalink
Search a 2D matrix
Browse files Browse the repository at this point in the history
  • Loading branch information
Sumanshu-Nankana committed Oct 28, 2023
1 parent 6ddfd11 commit 24821cc
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions Leetcode - 74 # Search a 2D Matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Solution-1
# Check which row target element is and then apply Binary Search in that particular row
# Time complexity m*log(n)

class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix) # number of rows
n = len(matrix[0]) # number of cols

for row in range(m):
# if element is in a row
if target >= matrix[row][0] and target <= matrix[row][-1]:
# Perform Binary Search
left = 0
right = n - 1

while left <= right:
mid = (left + right) // 2

if matrix[row][mid] == target:
return True

elif matrix[row][mid] < target:
left = mid + 1

else:
right = mid - 1
return False


# Solution-2
# In above solution, we are checking all rows
# we know all rows are also Sorted
# So we can apply Binary Search in Rows as well, to find the exact row
# Then apply Binary Search in that row (to find target) - same as above.

class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
m = len(matrix) # number of rows
n = len(matrix[0]) # number of cols

top, bottom = 0, n - 1

# Apply Binary search on rows to find in whc=ich row
# element resides
while top <= bottom:
row = (top + bottom) // 2
if target > matrix[row][-1]:
top = row + 1
elif target < matrix[row][0]:
bottom = row - 1
else:
break

# Once we find the row
# apply Binary Search in that row.
if top <= bottom:
row = (top + bottom) // 2
left, right = 0, cols - 1
while left <= right:
mid = (left + right) // 2
if matrix[row][mid] == target:
return True
elif matrix[row][mid] < target:
left = mid + 1
else:
right = mid - 1

return False

0 comments on commit 24821cc

Please sign in to comment.