Find First and Last Position of Element in Sorted Array

MediumBinary Search · Lower / Upper Bound🧩 Binary SearchLeetCode #34 ↗Updated

Problem

You get an array nums sorted in non-decreasing order (duplicates allowed) and a target. Return the indices [first, last] of the leftmost and rightmost occurrence of target, or [-1, -1] if it is absent. Aim for O(log n) time.
Input[5,7,7,8,8,10], t=8Output[3,4]
Input[5,7,7,8,8,10], t=6Output[-1,-1]
Input[], t=0Output[-1,-1]

0 ≤ n ≤ 105  ·  -109 ≤ nums[i], target ≤ 109  ·  nums is sorted  ·  Required: O(log n).

Try it yourself

Java
class Solution {
    public int[] searchRange(int[] nums, int target) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Don't stop when nums[mid] == target — keep shrinking toward one side. Biasing left on equality finds the first index, biasing right finds the last: two clean O(log n) boundary searches.
PatternBinary Search

Instinct Sorted data, a rotated array, or find the min/max X that works where a yes/no test flips only once - halve the search space every step.

Memory hack Find the fence - every candidate reads NO NO NO YES YES, and binary search just walks to where the fence stands.

Open the Binary Search guide →

Approaches

Brute ForceLinear Scan

Time O(n)Space O(1)

Walk the array once. The first time we see target we record first; every match updates last. Ignores the sorted order entirely.

Java
public int[] searchRange(int[] nums, int target) {
    int first = -1, last = -1;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == target) {
            if (first == -1) first = i;
            last = i;
        }
    }
    return new int[]{first, last};
}

Trivially correct, but O(n) violates the required O(log n).

At a glance

LevelApproachTimeSpace
Brute ForceLinear ScanO(n)O(1)
BetterBinary Search + Expand OutwardO(log n + k)O(1)
OptimalTwo Boundary Binary SearchesO(log n)O(1)
Common pitfalls
  • Returning as soon as nums[mid] == target — that's a match, not the boundary.
  • Skipping the final check — left may be n or point at a different value.
  • Using (l + r) / 2 — can overflow; prefer l + (r - l) / 2.
Interview tips
  • Name it: first = lower bound, last = upper bound − 1.
  • Point out why find-then-expand is O(n) on [8,8,8,...].
  • Test with empty array, single element, and target smaller/larger than all values.
Pattern
Boundary binary search → sorted data with duplicates and you need the first/last position satisfying a condition.
My notes saved in this browser