Find First and Last Position of Element in Sorted Array in Python

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        # Function to find the first occurrence of the target
        def findFirst(nums, target):
            left, right = 0, len(nums) - 1
            first_occurrence = -1
            while left <= right:
                mid = left + (right - left) // 2
                if nums[mid] == target:
                    first_occurrence = mid
                    right = mid - 1  # Continue searching to the left
                elif nums[mid] < target:
                    left = mid + 1
                else:
                    right = mid - 1
            return first_occurrence

        # Function to find the last occurrence of the target
        def findLast(nums, target):
            left, right = 0, len(nums) - 1
            last_occurrence = -1
            while left <= right:
                mid = left + (right - left) // 2
                if nums[mid] == target:
                    last_occurrence = mid
                    left = mid + 1  # Continue searching to the right
                elif nums[mid] < target:
                    left = mid + 1
                else:
                    right = mid - 1
            return last_occurrence

        # Handle edge case of empty array
        if not nums:
            return [-1, -1]

        return [findFirst(nums, target), findLast(nums, target)]

PrevNext