← DiffPush

First and last position

Baseline Binary Search · 1D Arrays O(log n) · O(1)

Bounding a Fault Window in a Sorted Event Log

A monitoring system keeps millions of log entries sorted by an internal fault code, and an on-call engineer needs the full span of one specific code. Because the code repeats, its first and last entries must both be found. If the code never appears, the answer is an empty span.

Input: An array nums of n integers sorted in non-decreasing order, and an integer target.

Output: A two-element array [first, last] of 0-indexed positions bounding every occurrence of target, or [-1, -1] when target is absent.

Constraints

Examples

Example 1

Input: {"nums":[5,7,7,8,8,10],"target":8}
Output: [3,4]
The code 8 occupies two adjacent entries at indices 3 and 4.

Example 2

Input: {"nums":[5,7,7,8,8,10],"target":6}
Output: [-1,-1]
Code 6 never appears in the log, so both bounds report -1.

Solve this in your browser →

Also on LeetCode ↗