diff --git a/data_structures/Binary search algo/search_insert_position.py b/data_structures/Binary search algo/search_insert_position.py new file mode 100644 index 000000000000..7ada2f4e33bb --- /dev/null +++ b/data_structures/Binary search algo/search_insert_position.py @@ -0,0 +1,28 @@ +from typing import List + + +def search_insert(nums: List[int], target: int) -> int: + """ + Finds the index to insert a target value into a sorted list. + + If the target is found, its index is returned. Otherwise, returns the + index where it would be if it were inserted in order. + + Args: + nums: A sorted list of integers. + target: The integer to search for. + + Returns: + The index for the target value. + """ + left, right = 0, len(nums) - 1 + + while left <= right: + mid = (left + right) // 2 + if nums[mid] == target: + return mid + elif nums[mid] < target: + left = mid + 1 + else: + right = mid - 1 + return left diff --git a/data_structures/Binary search algo/search_range.py b/data_structures/Binary search algo/search_range.py new file mode 100644 index 000000000000..8234dc66a830 --- /dev/null +++ b/data_structures/Binary search algo/search_range.py @@ -0,0 +1,40 @@ +from typing import List + + +def search_range(nums: List[int], target: int) -> List[int]: + """ + Finds the first and last position of a given target value in a sorted array. + + Args: + nums: A sorted list of integers. + target: The integer to search for. + + Returns: + A list containing the starting and ending index of the target. + Returns [-1, -1] if the target is not found. + """ + + def find_bound(is_first: bool) -> int: + """Helper to find the leftmost or rightmost occurrence of the target.""" + left, right = 0, len(nums) - 1 + bound = -1 + while left <= right: + mid = (left + right) // 2 + if nums[mid] == target: + bound = mid + if is_first: + right = mid - 1 # Continue searching on the left + else: + left = mid + 1 # Continue searching on the right + elif nums[mid] < target: + left = mid + 1 + else: + right = mid - 1 + return bound + + first_bound = find_bound(True) + if first_bound == -1: + return [-1, -1] + + last_bound = find_bound(False) + return [first_bound, last_bound]