Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in order to less than O(n).
If the target is not found in the array, return [-1, -1].
Constraints:
1 <= t <= 100
1 <= n <= 1000000
Example:
Test case 1:
Input:
arr = [5,6,7,8,8,10]
target = 8
Output:
range is : [3, 4]
Test case 2:
Input:
arr = [5,7,7,8,8,10]
target = 6
Output:
range is: [-1,-1]
Explanation:
Though the above solutions are self-explanatory,
still for the first test case,
For the first test case,
Target is first present at index 3 and
last one at 4. (0-based indexing)
For the second test case,
Target is not at all present and
hence range is [-1,-1]
It's quite similar to binary search. The modification is to not to stop when you get the target find. Search for the upper and lower elements to check if they are the same or not.
Here goes the full algorithm,
return result;
C++ Implementation:
Output: