sagelearnai

Find First and Last Position of Element in Sorted Array

Difficulty: Medium · Pattern: Binary Search · LeetCode #34

Given sorted nums, return [first, last], the first and last indices of target, or [−1, −1] if absent. O(log n).

Examples

text
nums = [5, 7, 7, 8, 8, 10], target = 8  →  [3, 4]
nums = [5, 7, 7, 8, 8, 10], target = 6  →  [−1, −1]
nums = [], target = 0                   →  [−1, −1]

Hints

  1. Find the first index with value ≥ target and the first index with value > target.

Approach

lo = lowerBound(target) (the first index ≥ target). If it's out of range or nums[lo] != target, return [−1, −1]. Otherwise the last position is lowerBound(target + 1) − 1 (or an upper-bound search). Two O(log n) searches.

Complexity

Time: O(log n). Space: O(1).

Python solution
def searchRange(nums, target):
    def lower(x):
        lo, hi = 0, len(nums)
        while lo < hi:
            mid = (lo + hi) // 2
            if nums[mid] < x: lo = mid + 1
            else: hi = mid
        return lo
    a = lower(target)
    if a == len(nums) or nums[a] != target:
        return [-1, -1]
    return [a, lower(target + 1) - 1]
JavaScript solution
function searchRange(nums, target) {
  const lower = (x) => { let lo = 0, hi = nums.length; while (lo < hi) { const m = (lo + hi) >> 1; if (nums[m] < x) lo = m + 1; else hi = m; } return lo; };
  const a = lower(target);
  if (a === nums.length || nums[a] !== target) return [-1, -1];
  return [a, lower(target + 1) - 1];
}