Find First and Last Position of Element in Sorted Array
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.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 3:
Input: nums = [], target = 0
Output: [-1,-1]
Constraints:
0 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
nums
is a non-decreasing array.-10^9 <= target <= 10^9
Solution
We want to find two positions, first_pos
and last_pos
of the target
in nums
.
For the first_pos
, we want to find the leftmost target
. So we will do binary search on nums
,
and whenever we find target
, we search for its left side to see whether there is another target
on the left while keeping track of the leftmost seen first_pos
.
Similarly, we want to find the rightmost target
in nums
to be last_pos
.
So when we see a target
, we search for its right side and record the last_pos = current index
.
If the current element is not target
, then ordinary binary search will lead us to the correct searching side.
def searchRange(self, nums, target):
left, right = 0, len(nums)-1
first_pos, last_pos = -1, -1
# find first pos
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
first_pos = mid
right = mid - 1
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
#find last pos
left, right = 0, len(nums)-1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
last_pos = mid
left = mid+1
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return (first_pos, last_pos)
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorWhich of the following uses divide and conquer strategy?
Recommended Readings
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!