/34. Find First and Last Index of Target in Sorted Array

34. Find First and Last Index of Target in Sorted Array

Medium
Arrays48.5% acceptance

Given a non-decreasing integer array data and an integer value query, return a list containing the first index and last index where query occurs in data. If query does not exist in data, return [-1, -1]. The solution must run in O(log n) time.

Example 1

Input: data = [2, 4, 4, 4, 6, 7], query = 4

Output: [1, 3]

Explanation: The value 4 appears at indices 1, 2, and 3.

Example 2

Input: data = [1, 2, 3, 4, 5], query = 3

Output: [2, 2]

Explanation: The value 3 appears only at index 2.

Example 3

Input: data = [1, 1, 1, 1], query = 2

Output: [-1, -1]

Explanation: The value 2 does not appear in the array.

Constraints

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

Case 1

Input: data = [0, 1, 2, 2, 2, 3, 4], query = 2

Expected: [2, 4]

Case 2

Input: data = [10, 20, 30, 40, 50], query = 60

Expected: [-1, -1]

Case 3

Input: data = [], query = 5

Expected: [-1, -1]

Case 4

Input: data = [-5, -5, -5, 0, 1], query = -5

Expected: [0, 2]

Case 5

Input: data = [7], query = 7

Expected: [0, 0]