34. Find First and Last Position of Element in Sorted Array
Asked at 30Meta74Apple65Bloomberg64Amazon62Microsoft53Google53tcs57TikTok53Nvidia39Instacart100Splunk100Tinkoff100Applied Intuition73LinkedIn71NetApp68Airtel68Capgemini62Turing55EPAM Systems51Oracle49Citadel47Accenture44Atlassian42Zoho42PayPal42Infosys39DE Shaw38Uber35Goldman Sachs28Salesforce28
Problem
nums is sorted in non-decreasing order. Return the first and last index of target, or [-1,-1] if it doesn't occur, in O(log n).
Example: nums = [5,7,7,8,8,10], target = 8 → [3,4]
first = lowerBound(target), last = lowerBound(target + 1) − 1. Check first actually holds target.
Complexity: O(log n).
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def lower(t):
lo, hi = 0, len(nums)
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] >= t:
hi = mid
else:
lo = mid + 1
return lo
a = lower(target)
if a == len(nums) or nums[a] != target:
return [-1, -1]
return [a, lower(target + 1) - 1]
assert Solution().searchRange([5, 7, 7, 8, 8, 10], 8) == [3, 4]
assert Solution().searchRange([5, 7, 7, 8, 8, 10], 6) == [-1, -1]
assert Solution().searchRange([], 0) == [-1, -1]
class Solution {
public int[] searchRange(int[] nums, int target) {
int a = lower(nums, target);
if (a == nums.length || nums[a] != target) return new int[]{-1, -1};
return new int[]{a, lower(nums, target + 1) - 1};
}
private int lower(int[] nums, int t) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] >= t) hi = mid; else lo = mid + 1;
}
return lo;
}
}
func searchRange(nums []int, target int) []int {
lower := func(t int) int { // first index with nums[i] >= t
lo, hi := 0, len(nums)
for lo < hi {
mid := lo + (hi-lo)/2
if nums[mid] >= t {
hi = mid
} else {
lo = mid + 1
}
}
return lo
}
a := lower(target)
if a == len(nums) || nums[a] != target {
return []int{-1, -1}
}
return []int{a, lower(target+1) - 1}
}