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 O(log n) runtime complexity.
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Input: nums = [], target = 0
Output: [-1,-1]
nums is a non-decreasing array.The simplest way to find the first and last positions of a target element in a sorted array is to perform a linear scan. We traverse the array from the beginning to end and record the positions when the target element matches.
To improve efficiency, consider using binary search. By performing two separate binary searches, we can find the first occurrence and the last occurrence of the target element. The key is to tailor the binary search condition to continue searching for the first or last position once a target element is found.
We can further optimize by combining the searches for the first and last occurrence into a single binary search. We check for both conditions in a single run, further reducing complexity in terms of constant factors. This method uses binary search with a twist by utilizing stricter compared conditions.