Find First and Last Position of Element in Sorted Array
Given a sorted list of integers arr
in ascending order, determine the first and last positions where a specified key
appears.
Your solution should aim for a runtime complexity of approximately O(log n).
If the key
is not present in the list, return [-1, -1]
.
Input: arr = [2, 4, 4, 6, 6, 9], key = 6 Output: [3, 4]
Input: arr = [2, 4, 4, 6, 6, 9], key = 5 Output: [-1, -1]
Input: arr = [1, 1, 2, 3, 4, 4, 4, 5], key = 4 Output: [4, 6]
arr
≤ 15,000arr
≤ 105arr
is sorted in ascending order