Problem 34 · LeetCode 34(opens in a new tab)
Find First and Last Position of Element in Sorted Array
MediumArrays
You are given nums, a list of integers sorted from smallest to largest (equal values may sit next to each other), and a value target.
Return a pair [first, last]: the lowest and the highest index that hold target. If target does not appear at all, return [-1, -1].
Your algorithm has to run in O(log n) time.
Example 1
Input: nums = [2, 4, 4, 4, 9, 11], target = 4 Output: [1, 3] Why: the three 4s fill indices 1 to 3
2 more examples and the constraints
Example 2
Input: nums = [1, 3, 3, 6], target = 5 Output: [-1, -1] Why: 5 would go between 3 and 6, but it is not there
Example 3
Input: nums = [], target = 7 Output: [-1, -1] Why: an empty list holds nothing
Constraints
- 0 ≤ length of nums ≤ 100,000
- Every number and the target are between −1,000,000,000 and 1,000,000,000
- nums never decreases from left to right
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Linear scanO(n)
- Two lower-bound searchesO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers | Verdict |
|---|---|---|---|
| Linear scan | O(n) | Correct, but breaks the O(log n) rule | |
| Two lower-bound searches | O(log n) | Best; about 34 reads |
n = length of nums.
Edge cases to test
- Empty array. [] gives [-1, -1];
lowerreturns 0, which is past the end. - Target larger than everything.
lowerreturns n, so checkfirst == nbefore readingnums[first]. - Every value is the target. [6, 6, 6] with target 6 gives [0, 2].
- One copy only. first and last are the same index.
- Target at the integer limit. target = 1,000,000,000 makes
target + 1still fit in 32 bits, but the Java and C++ code widen it anyway.
Common mistakes
- Stopping the binary search at the first match and then walking left and right, which is O(n) on an array of equal values.
- Reading
nums[first]without checking thatfirstis inside the array. - Mixing
hi = midandhi = mid − 1between the two searches and getting an off-by-one.
How to talk through it
- 1Clarify. Can the array be empty? Can values repeat? Should a missing target give [-1, -1]?
- 2Give the scan. One pass finds both ends in O(n); say it ignores the sorting.
- 3Name the boundary. The start of the run is the first value ≥ target; the end is just before the first value ≥ target + 1.
- 4Code one helper. Write
lower(x)with a half-open range and call it twice. - 5Test out loud. Run an empty array, a missing target, and an array of all copies.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?