By Long Luo

This article is the solution 3 Approaches: DP, Recursion, Math of Problem 34. Find First and Last Position of Element in Sorted Array.

Here shows 2 Approaches to slove this problem: Brute Force and Binary Search.

Brute Force

The easiest method is scan the array from left to right. Use two variables to record the index of the first and last element $\textit{target}$. The time complexity is $O(n)$.

Analysis

• Time Complexity: $O(n)$
• Space Complexity: $O(1)$

Binary Search

Since the array is sorted in ascending order, so we can binary search to speed up the search.

Considering the start and end positions of target, in fact, what we are looking for is “the first position in the array equal to target” (recorded as $\textit{leftIdx}$ ) and “the first position greater than The position of target minus one” (recorded as $\textit{rightIdx}$ ).

In binary search, looking for $\textit{leftIdx}$ is to find the first index greater than or equal to target in the array, and looking for $\textit{rightIdx}$ is to find the first index greater than target in the array index of target, then decrement the index by one.

Finally, since $\textit{target}$ may not exist in the array, we need to re-check the two indices we got $\textit{leftIdx}$ and $\textit{rightIdx}$ to see if they meet the conditions, if so It returns $[\textit{leftIdx}, \textit{rightIdx}]$, if it does not match, it returns $[-1, -1]$.

Analysis

• Time Complexity: $O(logn)$
• Space Complexity: $O(1)$

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗