SDE & MLE Prep

34. Find First and Last Position of Element in Sorted Array

Problem

nums is sorted in non-decreasing order. Return the first and last index of target, or [-1,-1] if it doesn't occur, in O(log n).

Example: nums = [5,7,7,8,8,10], target = 8 → [3,4]

first = lowerBound(target), last = lowerBound(target + 1) − 1. Check first actually holds target.

Complexity: O(log n).

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def lower(t):
            lo, hi = 0, len(nums)
            while lo < hi:
                mid = (lo + hi) // 2
                if nums[mid] >= t:
                    hi = mid
                else:
                    lo = mid + 1
            return lo

        a = lower(target)
        if a == len(nums) or nums[a] != target:
            return [-1, -1]
        return [a, lower(target + 1) - 1]