InferenceAI

Enter at least two characters to search.

Start free

First and Last Index

mediumBinary Search25 min25 XP

Given a sorted list nums and a target, return [first, last]: the first and last index of target, or [-1, -1] if it is absent.

Requirements

  • O(log⁡n)O(\log n) time: run two binary searches (lower bound and upper bound).

Constraints

  • 0≤n≤1050 \le n \le 10^5

Examples

EXAMPLE WALKTHROUGHtwo copies

A guided view of the published example, not a trace of your code.

INPUT[[5,7,7,8,8,10],8]
TASKfirst_and_last_index()
EXPECTED OUTPUT[3,4]

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [5,7,7,8,8,10], target = 8

Output: [3,4]

Explanation: two copies

Input: nums = [5,7,7,8,8,10], target = 6

Output: [-1,-1]

Explanation: absent

Input: nums = [], target = 0

Output: [-1,-1]

Explanation: empty

Hint 1

Lower bound: the first index whose value is >= target.

Hint 2

Upper bound: the first index whose value is > target; the last occurrence is one before it.

Topics

DSABinary SearchPython