Problem
Given an array of integers nums
sorted in non-decreasing order, find the starting and ending position of a given target
value.
If target
is not found in the array, return [-1, -1]
.
You must write an algorithm with O(log n)
runtime complexity.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Similar problem
Count frequency of target element in sorted array
Solution
Method 1 - Brute Force
The Naive Approach is to run a for loop and check given elements in array.
- Iterate through the array with a for loop from i = 0 to n-1.
- Initialize
first
andlast
to -1. - When the element is found for the first time, set
first
to i. - Update
last
to i each time the element is found. - Print
first
andlast
.
- ⏰ Time complexity:
O(n)
, wheren
is number of elements in array. - 🧺 Space complexity:
O(1)
Method 2 - Using Binary Search to Find First and Last Separately
We have already solved 2 problems:
- Find first position of target element in sorted array
- Find last position of target element in sorted array
Then, we can just call respective methods, and return the position.
Code
|
|
Complexity
- ⏰ Time complexity:
O(log n)
- 🧺 Space complexity:
O(1)