Problem Description
Given a sorted array of integers and a target value, the goal is to find the starting and ending position of the target value in the array. If the target is not present, return [-1, -1]. The solution must run in O(log n) time.
Key Insights
- The array is sorted, allowing the use of binary search.
- Two binary searches can efficiently find the leftmost (first) and rightmost (last) indices of the target.
- Handling edge cases where the target is not present by checking bounds.
Space and Time Complexity
Time Complexity: O(log n)
Space Complexity: O(1)
Solution
The approach is to use binary search twice:
- The first binary search finds the leftmost occurrence of the target by continuing to search in the left half even after finding the target.
- The second binary search finds the rightmost occurrence by searching in the right half. The algorithm maintains pointers for the current search bounds and narrows the search space using comparisons. If the target is not found during the first binary search, the solution immediately returns [-1, -1]. This method leverages the sorted property of the array, ensuring O(log n) time complexity with constant extra space.