Ecommet

Find First and Last Position of Element in Sorted Array

Medium Problem 42 of 151 Java and Python

Problem

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of target. If it is not found, return [-1, -1].

The algorithm must run in O(log n) time.

Example 1

Input
nums = [5, 7, 7, 8, 8, 10], target = 8
Output
[3, 4]

Example 2

Input
nums = [5, 7, 7, 8, 8, 10], target = 6
Output
[-1, -1]

Constraints

  • 0 ≤ nums.length ≤ 10⁵
  • nums is sorted in non-decreasing order.

Explanation

An ordinary binary search stops at any copy of the target. To find the first copy, keep searching left even after a match; for the last copy, keep searching right.

Equivalently: the first position is the first index with nums[i] >= target, and the last is one before the first index with nums[i] > target.

Approach 1 · Naive

Linear scan

  • Time O(n)
  • Space O(1)

Scan once, recording the first and last index where the value equals the target.

  1. For each index with nums[i] == target: set first if unset, and always update last.
Java
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int first = -1;
        int 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 };
    }
}
Python
class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        first = last = -1
        for i, num in enumerate(nums):
            if num == target:
                if first == -1:
                    first = i
                last = i
        return [first, last]

Approach 2 · Optimal

Two boundary searches

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

Write one helper that finds the first index whose value is >= x. The first position is lower(target); the last is lower(target + 1) - 1.

  1. lower(x): lo = 0, hi = n; while lo < hi, if nums[mid] < x then lo = mid + 1 else hi = mid. Return lo.
  2. start = lower(target). If start == n or nums[start] != target, return [-1, -1].
  3. Return [start, lower(target + 1) - 1].
Java
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int start = lower(nums, target);
        if (start == nums.length || nums[start] != target) {
            return new int[] { -1, -1 };
        }
        return new int[] { start, lower(nums, target + 1) - 1 };
    }

    // First index whose value is >= x (nums.length if none).
    private int lower(int[] nums, int x) {
        int lo = 0;
        int hi = nums.length;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] < x) {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        return lo;
    }
}
Python
class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        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

        start = lower(target)
        if start == len(nums) or nums[start] != target:
            return [-1, -1]
        return [start, lower(target + 1) - 1]

Complexity compared

ApproachTimeSpace
Naive Linear scanO(n)O(1)
Optimal Two boundary searchesO(log n)O(1)

Key takeaways

  • "First index ≥ x" (lower bound) is the most reusable binary search. Python's bisect_left and C++'s lower_bound are exactly this.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem