Skip to content
DSA Patterns
Menu
Language
Binary SearchLC #342 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Find First and Last Position of Element in Sorted Array

Problem (restated)

Find start and end indices of target in a sorted array, or [-1,-1]. O(log n).

Intuition

Two lower_bound searches for target and target+1.

Approaches

Lower & upper bound

Unverified
Time O(log n)Space O(1)

Idea. left = lower_bound(target); right = lower_bound(target+1)-1.

Walkthrough. [5,7,7,8,8,10], 8 → [3,4].

Trade-offs. Linear scan violates the log-time constraint.

Solution
export function searchRange(nums: number[], target: number): number[] {
  const lower = (t: number) => {
    let lo = 0, hi = nums.length;
    while (lo < hi) {
      const mid = lo + ((hi - lo) >> 1);
      if (nums[mid]! < t) lo = mid + 1; else hi = mid;
    }
    return lo;
  };
  const left = lower(target);
  if (left === nums.length || nums[left] !== target) return [-1, -1];
  return [left, lower(target + 1) - 1];
}
export function searchRange(nums: number[], target: number): number[] {
  const lower = (t: number) => {
    let lo = 0, hi = nums.length;
    while (lo < hi) {
      const mid = lo + ((hi - lo) >> 1);
      if (nums[mid]! < t) lo = mid + 1; else hi = mid;
    }
    return lo;
  };
  const left = lower(target);
  if (left === nums.length || nums[left] !== target) return [-1, -1];
  return [left, lower(target + 1) - 1];
}

Template connection

Two lower bounds from the same template: the first index of target, and the first index of target + 1. The span between them is the range. If the first bound is not target, the answer is [-1, -1].

Reflection

  • The same target needs a lower bound and an upper bound. What changes between hi = mid and lo = mid + 1?
  • A missing target returns [-1, -1]. Expanding linearly from the first hit can become O(n). Why is that out?
  • Target at the far left or the far right: can mid walk off the array?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

First and last index of 8 in a sorted array. Two bound searches.

5
0
7
1
7
2
8
3
8
4
10
5

target = 8

Key:CurrentActive rangeMatchSettledEliminated