All problems

Find First and Last Position of Element

Medium · binary search

You are given a list nums of integers sorted in ascending order. Values may repeat. You are also given an integer target.

Return a list of two numbers [first, last]: the index of the first and the index of the last occurrence of target in nums. If target appears only once, both numbers are the same. If target does not appear at all, return [-1, -1].

Examples

Example 1

Input: nums = [1, 3, 3, 3, 6, 8], target = 3

Output: [1, 3]

The 3s fill indices 1, 2 and 3.

Example 2

Input: nums = [1, 3, 3, 3, 6, 8], target = 6

Output: [4, 4]

6 appears once, at index 4.

Example 3

Input: nums = [1, 3, 3, 3, 6, 8], target = 5

Output: [-1, -1]

5 is not in the list.

Constraints