Find First and Last Position of Element in Sorted Array
Master this topic with zero to advance depth.
Find First and Last Position of Element in Sorted Array
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with runtime complexity.
Examples
Level I: Brute Force (Two Pass Linear Scan)
Intuition
Scan from the left to find the first occurrence, and from the right to find the last. While simple, it takes time, missing the efficiency of sorted bounds.
Detailed Dry Run
nums = [5,7,7,8,8,10], target = 8
- First: index 0(5), 1(7), 2(7), 3(8) -> 3
- Last: index 5(10), 4(8) -> 4 Result: [3, 4]
Level II: Optimal (Built-in Library)
Intuition
Most languages provide built-in binary search functions (like bisect_left and bisect_right in Python, or lower_bound/upper_bound in C++). These are highly optimized and should be used in production.
Detailed Dry Run
nums = [5,7,7,8,8,10], target = 8
lower_boundfinds first index where val >= 8: index 3.upper_boundfinds first index where val > 8: index 5.- Result: [3, 5-1=4].
Level III: Optimal (Two Binary Searches)
Intuition
We perform two separate binary searches. In the first search (find left bound), when nums[mid] == target, we continue searching left (high = mid - 1). In the second search (find right bound), we continue searching right (low = mid + 1).
Detailed Dry Run
nums = [5,7,7,8,8,10], target = 8
- Search First:
mid = 2 (val 7). 7 < 8 -> L=3.mid = 4 (val 8). 8==8 -> save 4, R=3.mid = 3 (val 8). 8==8 -> save 3, R=2. End. Result index 3. - Search Last: Similar logic searching right. Result index 4.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.