First and Last Occurrences
Problem Statement Given a sorted array arr (which may contain duplicates), find the first and last occurrences of an element x. If x is not present in the array, return [-1, -1]. Examples: Input: a...

Source: DEV Community
Problem Statement Given a sorted array arr (which may contain duplicates), find the first and last occurrences of an element x. If x is not present in the array, return [-1, -1]. Examples: Input: arr = [1, 3, 5, 5, 5, 5, 67, 123, 125], x = 5 Output: [2, 5] Input: arr = [1, 3, 5, 5, 5, 5, 7, 123, 125], x = 7 Output: [6, 6] Input: arr = [1, 2, 3], x = 4 Output: [-1, -1] Constraints: 1 ≤ arr.size() ≤ 10^6 1 ≤ arr[i], x ≤ 10^9 Approach: Binary Search Since the array is sorted, binary search allows us to efficiently find the first and last occurrences of x. Steps: First Occurrence: Perform binary search. If arr[mid] == x, move the high pointer to mid - 1 to check if x occurs earlier. Last Occurrence: Perform binary search. If arr[mid] == x, move the low pointer to mid + 1 to check if x occurs later. This ensures O(log n) time complexity for each search, perfect for large arrays. Python CODE from typing import List class Solution: def find(self, arr: List[int], x: int) -> List[int]: n = l