thiagowfx's avatar

Β¬ just serendipity πŸ€ (not just serendipity)

ByteByteGo: First and Last Occurrences of a Number

β€’ 62 words β€’ 1 min β€’ updated

ByteByteGo: First and Last Occurrences of a Number:

python
import bisect
from typing import List

def first_and_last_occurrences_of_a_number(nums: List[int], target: int) -> int:
    if not nums:
        return [-1, -1]

    left = bisect.bisect_left(nums, target)
    right = bisect.bisect_right(nums, target)

    if (left < len(nums) and nums[left] == target) and (right > 0 and nums[right - 1] == target):
        return [left, right - 1]

    return [-1, -1]