Search Insert Position in Python

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        """
        Finds the index of the given target in a sorted array. If the target is not found,
        returns the index where it would be inserted to maintain the order.

        :param nums: List[int], sorted array of integers
        :param target: int, the target integer to find or insert
        :return: int, the index of the target or the insertion position
        """
        # Initialize the start and end pointers
        start = 0
        end = len(nums) - 1

        # Continue the loop until the start and end pointers cross
        while start <= end:
            # Calculate the mid index
            mid = (start + end) // 2

            # If the target is found at the mid index, return this index
            if nums[mid] == target:
                return mid

            # If the target is less than the element at mid, move the end pointer to mid - 1
            if target < nums[mid]:
                end = mid - 1
            else:
                # If the target is greater, move the start pointer to mid + 1
                start = mid + 1

        # If the target is not found, start will be at the correct insertion index
        return start

PrevNext