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

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

Medium
Arrays48.5% acceptance

Given a non-decreasing integer array arr and an integer value x, return a list containing the indices of the first and last occurrence of x in arr. If x does not exist in arr, return [-1, -1]. The algorithm must run in O(log n) time.

Example 1

Input: arr = [2, 4, 4, 4, 5, 6], x = 4

Output: [1, 3]

Explanation: The value 4 appears from index 1 to 3.

Example 2

Input: arr = [1, 2, 3, 4, 5], x = 7

Output: [-1, -1]

Explanation: The value 7 does not appear in arr.

Example 3

Input: arr = [], x = 1

Output: [-1, -1]

Explanation: Empty array, so x cannot be found.

Example 4

Input: arr = [7, 7, 7, 7], x = 7

Output: [0, 3]

Explanation: All elements are 7, so first index is 0 and last is 3.

Constraints

  • 0 <= len(arr) <= 105
  • -109 <= arr[i] <= 109 for all i
  • arr is sorted in non-decreasing order
  • -109 <= x <= 109
Python (current runtime)

Case 1

Input: arr = [0, 1, 2, 2, 2, 3], x = 2

Expected: [2, 4]

Case 2

Input: arr = [1, 1, 2, 3, 4, 5], x = 1

Expected: [0, 1]

Case 3

Input: arr = [10, 20, 30, 40, 50], x = 40

Expected: [3, 3]

Case 4

Input: arr = [5, 6, 7, 8, 9], x = 10

Expected: [-1, -1]

Case 5

Input: arr = [100], x = 100

Expected: [0, 0]