diff --git a/DIRECTORY.md b/DIRECTORY.md index 0f9859577493..6eb547fb6216 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -173,6 +173,8 @@ * [Volume Conversions](conversions/volume_conversions.py) * [Weight Conversion](conversions/weight_conversion.py) +## [Coordinate Compression](/coordinate_compression.py) + ## Data Compression * [Burrows Wheeler](data_compression/burrows_wheeler.py) * [Coordinate Compression](data_compression/coordinate_compression.py) @@ -1243,6 +1245,7 @@ ## Searches * [Binary Search](searches/binary_search.py) + * [Binary Search With Duplicates](searches/binary_search_with_duplicates.py) * [Binary Tree Traversal](searches/binary_tree_traversal.py) * [Double Linear Search](searches/double_linear_search.py) * [Double Linear Search Recursion](searches/double_linear_search_recursion.py) diff --git a/coordinate_compression.py b/coordinate_compression.py new file mode 100644 index 000000000000..d135277496e4 --- /dev/null +++ b/coordinate_compression.py @@ -0,0 +1,10 @@ +def compress(value): + if value not in coordinate_map: + raise ValueError(f"{value} not found in coordinate map") + return coordinate_map[value] + + +def decompress(index): + if index < 0 or index >= len(original_values): + raise ValueError(f"Index {index} is out of bounds") + return original_values[index] diff --git a/searches/binary_search_with_duplicates.py b/searches/binary_search_with_duplicates.py new file mode 100644 index 000000000000..2b3dab20f9b3 --- /dev/null +++ b/searches/binary_search_with_duplicates.py @@ -0,0 +1,21 @@ +def binary_search_first_occurrence(arr: list[int], target: int) -> int: + """ + Return the index of the first occurrence of target in a sorted list. + + >>> binary_search_first_occurrence([1, 2, 4, 4, 4, 5], 4) + 2 + >>> binary_search_first_occurrence([1, 2, 3], 5) + -1 + """ + left, right = 0, len(arr) - 1 + result = -1 + while left <= right: + mid = (left + right) // 2 + if arr[mid] == target: + result = mid + right = mid - 1 + elif arr[mid] < target: + left = mid + 1 + else: + right = mid - 1 + return result