22. First and Last Occurrences of x
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
I have used a binary search approach to find the first and last occurrences of the element x
in the given sorted array. Here are the steps:
Implement a lower_bound
function using binary search to find the first occurrence of x
.
The lower_bound
function will return the index of the first element greater than or equal to x
.
Check if the element at the index returned by lower_bound
is equal to x
. If not, return {-1, -1}
to indicate that x
is not present in the array.
Implement an upper_bound
function using binary search to find the last occurrence of x
.
The upper_bound
function will return the index of the first element greater than x
. Subtract 1 from this index to get the index of the last occurrence of x
.
Return a vector containing the indices of the first and last occurrences of x
.
Time Complexity: Both the lower_bound
and upper_bound
functions use binary search, which has a time complexity of O(log n)
, where n
is the size of the array. Thus, the overall time complexity of the find
function is O(log n).
Auxiliary Space Complexity: The find
function uses a constant amount of auxiliary space, so the space complexity is O(1)
.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.