22. First and Last Occurrences of x
The problem can be found at the following link: Question Link
My Approach
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 ofx
.The
lower_bound
function will return the index of the first element greater than or equal tox
.
Check if the element at the index returned by
lower_bound
is equal tox
. If not, return{-1, -1}
to indicate thatx
is not present in the array.Implement an
upper_bound
function using binary search to find the last occurrence ofx
.The
upper_bound
function will return the index of thefirst element greater than x
. Subtract 1 from this index to get the index of the last occurrence ofx
.
Return a vector containing the indices of the first and last occurrences of
x
.
Time and Auxiliary Space Complexity
Time Complexity: Both the
lower_bound
andupper_bound
functions use binary search, which has a time complexity ofO(log n)
, wheren
is the size of the array. Thus, the overall time complexity of thefind
function is O(log n).Auxiliary Space Complexity: The
find
function uses a constant amount of auxiliary space, so the space complexity isO(1)
.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 getlost01/gfg-potd repository.
Last updated