Skip to content
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

Adding Binary Search Algo Based on 2D Arrays #12100

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
36 changes: 36 additions & 0 deletions searches/peakelementin2D.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
def find_peak_util(matrix, left, right, row_count):

Check failure on line 1 in searches/peakelementin2D.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

searches/peakelementin2D.py:1:1: N999 Invalid module name: 'peakelementin2D'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file searches/peakelementin2D.py, please provide doctest for the function find_peak_util

Please provide return type hint for the function: find_peak_util. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: matrix

Please provide type hint for the parameter: left

Please provide type hint for the parameter: right

Please provide type hint for the parameter: row_count

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file searches/peakelementin2D.py, please provide doctest for the function find_peak_util

Please provide return type hint for the function: find_peak_util. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: matrix

Please provide type hint for the parameter: left

Please provide type hint for the parameter: right

Please provide type hint for the parameter: row_count

mid_col = (left + right) // 2

max_row_index = 0
for i in range(row_count):
if matrix[i][mid_col] > matrix[max_row_index][mid_col]:
max_row_index = i

if (
mid_col == 0
or matrix[max_row_index][mid_col] >= matrix[max_row_index][mid_col - 1]
) and (
mid_col == len(matrix[0]) - 1
or matrix[max_row_index][mid_col] >= matrix[max_row_index][mid_col + 1]
):
return matrix[max_row_index][mid_col]

if (
mid_col > 0
and matrix[max_row_index][mid_col - 1] > matrix[max_row_index][mid_col]
):
return find_peak_util(matrix, left, mid_col - 1, row_count)

return find_peak_util(matrix, mid_col + 1, right, row_count)


def find_peak(matrix):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file searches/peakelementin2D.py, please provide doctest for the function find_peak

Please provide return type hint for the function: find_peak. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: matrix

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file searches/peakelementin2D.py, please provide doctest for the function find_peak

Please provide return type hint for the function: find_peak. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: matrix

if not matrix or not matrix[0]:
return None
return find_peak_util(matrix, 0, len(matrix[0]) - 1, len(matrix))


matrix = [[10, 8, 10, 10], [14, 13, 12, 11], [15, 9, 11, 21], [16, 17, 19, 20]]

peak = find_peak(matrix)
print(f"Peak element is: {peak}")
72 changes: 72 additions & 0 deletions sorts/binarysearch_on_sorted_2d_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#!/usr/bin/env python3


def binary_search_2d(matrix: list[list[int]], target: int) -> tuple[int, int]:
"""
Searches for a target value in a 2D sorted array.

The matrix is sorted such that each row is in ascending order, and the
first element of each row is greater than the last element of the previous row.

Args:
matrix: A 2D list of integers sorted in ascending order.
target: The integer value to search for.

Returns:
A tuple (row_index, col_index) if found, otherwise (-1, -1).

Raises:
ValueError: If matrix is empty or not rectangular.

>>> binary_search_2d([[1, 3, 5], [7, 9, 11], [12, 13, 15]], 9)
(1, 1)
>>> binary_search_2d([[1, 3, 5], [7, 9, 11], [12, 13, 15]], 4)
(-1, -1)
>>> binary_search_2d([], 1) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: matrix must not be empty
>>> binary_search_2d([[1, 2], [3, 4, 5]], 3) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: matrix must be rectangular
"""
if not matrix or not matrix[0]:
raise ValueError("matrix must not be empty")

Check failure on line 36 in sorts/binarysearch_on_sorted_2d_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/binarysearch_on_sorted_2d_array.py:36:1: W293 Blank line contains whitespace
rows = len(matrix)
cols = len(matrix[0])

Check failure on line 39 in sorts/binarysearch_on_sorted_2d_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/binarysearch_on_sorted_2d_array.py:39:1: W293 Blank line contains whitespace
for row in matrix:
if len(row) != cols:
raise ValueError("matrix must be rectangular")

Check failure on line 43 in sorts/binarysearch_on_sorted_2d_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/binarysearch_on_sorted_2d_array.py:43:1: W293 Blank line contains whitespace
left, right = 0, rows * cols - 1

while left <= right:
mid = left + (right - left) // 2
mid_value = matrix[mid // cols][mid % cols]

if mid_value == target:
return mid // cols, mid % cols
elif mid_value < target:
left = mid + 1
else:
right = mid - 1

return -1, -1


if __name__ == "__main__":
import doctest

doctest.testmod()

# Example usage
matrix = [[1, 3, 5], [7, 9, 11], [12, 13, 15]]
target = 9
result = binary_search_2d(matrix, target)
if result == (-1, -1):
print(f"{target} was not found in the matrix.")
else:
print(f"{target} was found at position {result} in the matrix.")
Loading