Find First and Last Position of Element in Sorted Array - Problem
Search Range in Sorted Array
You are given a sorted array of integers and need to find the starting and ending positions of a specific target value. This is a classic problem that tests your understanding of binary search optimization.
The Challenge: Given an array
The Twist: You must solve this in O(log n) time complexity, which means a simple linear scan won't cut it!
Example:
Input:
Output:
This problem is fundamental for understanding binary search variations and is frequently asked in technical interviews at major tech companies.
You are given a sorted array of integers and need to find the starting and ending positions of a specific target value. This is a classic problem that tests your understanding of binary search optimization.
The Challenge: Given an array
nums sorted in non-decreasing order, find the first and last occurrence of a target value. If the target doesn't exist, return [-1, -1].The Twist: You must solve this in O(log n) time complexity, which means a simple linear scan won't cut it!
Example:
Input:
nums = [5,7,7,8,8,8,10], target = 8Output:
[3,5] (target 8 appears from index 3 to 5)This problem is fundamental for understanding binary search variations and is frequently asked in technical interviews at major tech companies.
Input & Output
example_1.py โ Basic Range Search
$
Input:
nums = [5,7,7,8,8,8,10], target = 8
โบ
Output:
[3,5]
๐ก Note:
Target 8 appears at indices 3, 4, and 5. The first occurrence is at index 3 and the last occurrence is at index 5, so we return [3,5].
example_2.py โ Target Not Found
$
Input:
nums = [5,7,7,8,8,8,10], target = 6
โบ
Output:
[-1,-1]
๐ก Note:
Target 6 does not exist in the array, so we return [-1,-1] as specified in the problem statement.
example_3.py โ Empty Array
$
Input:
nums = [], target = 0
โบ
Output:
[-1,-1]
๐ก Note:
The array is empty, so the target cannot be found. We return [-1,-1].
Constraints
- 0 โค nums.length โค 105
- -109 โค nums[i] โค 109
- nums is a non-decreasing array
- -109 โค target โค 109
- Follow up: Could you write an algorithm with O(log n) runtime complexity?
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
Set up two binary searches with left and right pointers
2
Find First Occurrence
When target found, continue searching left to find the earliest occurrence
3
Find Last Occurrence
When target found, continue searching right to find the latest occurrence
4
Return Range
Combine results to return [first, last] positions
Key Takeaway
๐ฏ Key Insight: Use two modified binary searches - one biased towards finding the leftmost occurrence, another biased towards finding the rightmost occurrence. This achieves O(log n) complexity by leveraging the sorted array property.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code