#34

Find First and Last Position of Element in Sorted Array

Medium Lower & upper bound

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the first and last index of target in a sorted array, or [-1, -1], in O(log n).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the first and last index of target.

Why this works: lowerBound(x) gives the first index with value ≥ x. First = lowerBound(target), last = lowerBound(target + 1) - 1.

Example: [5, 7, 7, 8, 8, 10], target 8

lowerBound(8) = 3lowerBound(9) = 5 → last 4[3, 4]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Finding one occurrence and then walking left/right linearly — O(n) when the value repeats a lot.

Solve on LeetCode ↗
Complexity
  • Time: O(log n).
  • Space: O(1).
Topic: Binary Search
🎬 Episodes 21–23: video coming soon