15% off all plans & roadmaps Use code

See plans

Find First and Last Position of Element in Sorted Array

Updated

TL;DR: Given a sorted array, return the first and last index of a target, or [-1, -1] when it is missing. Two binary searches solve it in O(log n) time. One finds the first index with a value at least the target. The other finds the first index with a value above it.

Problem

You get an array of integers nums sorted in non-decreasing order. Find the first and last index where the value target appears.

If target does not appear in the array, return [-1, -1].

Your 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]

Example 3

Input: nums = [], target = 0
Output: [-1,-1]

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums is a non-decreasing array.
  • -10^9 <= target <= 10^9

Constraints that matter

  • With n up to 10^5, a linear scan is too slow for the required O(log n) bound, so every step must discard a large part of the array.
  • The array is sorted, so all copies of target form one contiguous block. You only need the two edges of that block.
  • Values stay within 10^9 in size, so target + 1 still fits in a 32-bit signed integer. That makes a boundary search on target + 1 safe.
  • The array can be empty. Check the length before you read nums[first].

View on LeetCode

Hints

Hint 1

The sorted order is the key fact.

Hint 2

Check every index from left to right.

Solution

Intuition

The sorted order is the key fact. Every copy of target sits in one block, values left of the block are smaller, and values right of it are larger. Finding the two edges of that block is a boundary problem, and binary search solves boundary problems in logarithmic time.

Picture a sorted row of coat hooks, with all hooks of one size grouped together. The lowerBound search is a finger moving by halves to the first hook that is not smaller than the target.

This is the find first and last occurrence pattern. A plain binary search stops at the first match it sees, and that match can sit in the middle of the block. Change the question you ask at each probe, and you find an edge instead of a match.

Two edges mean two searches. The first index holding a value at least target is the start of the block. The first index holding a value greater than target is one past the end, so subtracting one gives the last index. If the start does not hold target, the block is empty and the answer is [-1, -1].

Watch the pattern animation

Worked example

Input: nums = [5, 7, 7, 8, 8, 10], target = 8
Output: [3, 4]
Explanation: The value 8 sits at indices 3 and 4. Index 2 holds a 7 and index 5 holds a 10, so the block of 8s starts at 3 and ends at 4.

Approach 1: Brute force

Check every index from left to right. Keep the first index where the value equals target, and move last forward on every later match. The scan never stops early, so it reads all n values even though the array is sorted.

Steps

  1. Set first and last to -1.
  2. Loop i from 0 to n - 1.
  3. If nums[i] equals target and first is still -1, set first to i.
  4. If nums[i] equals target, set last to i.
  5. Return [first, last].

Dry run

Start with first = -1 and last = -1, using nums = [5, 7, 7, 8, 8, 10] and target = 8.

  • i = 0: 5 is not 8. No change.
  • i = 1: 7 is not 8. No change.
  • i = 2: 7 is not 8. No change.
  • i = 3: 8 matches. first is -1, so first = 3. last = 3.
  • i = 4: 8 matches. first stays 3. last = 4.
  • i = 5: 10 is not 8. No change.

The scan ends with [3, 4].

Complexity

TimeO(n)
SpaceO(1)

Let n be the array length. The loop runs once per index, and each iteration does a constant amount of work, so the total is n constant-time steps. The loop cannot stop early, because a match near the end can still move last. The extra space is two integers and the loop index.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        first, last = -1, -1
        for i in range(len(nums)):
            if nums[i] == target:
                if first == -1:
                    first = i
                last = i
        return [first, last]

Approach 2: Binary search, then expand

What's slow: the brute force reads every element, but the sorted order tells you most positions cannot hold the target. The insight that fixes it: one binary search finds a single copy of target in O(log n) steps. Copies of the same value sit next to each other, so you can walk left and right from that copy until the value changes.

The walk costs one step per copy. That is cheap when the block is small, but it becomes the bottleneck when the block is large.

Steps

  1. Binary search for any index found where nums[found] equals target. If there is none, return [-1, -1].
  2. Move first left from found while the value to its left still equals target.
  3. Move last right from found while the value to its right still equals target.
  4. Return [first, last].

Dry run

Use nums = [5, 7, 7, 8, 8, 10] and target = 8.

  • Search: lo = 0, hi = 5, mid = 2. The value 7 is less than 8, so lo = 3.
  • Search: lo = 3, hi = 5, mid = 4. The value 8 matches, so found = 4.
  • Expand left: index 3 holds 8, so first = 3. Index 2 holds 7, so the walk stops.
  • Expand right: index 5 holds 10, so the walk stops. last stays 4.

The result is [3, 4].

Complexity

TimeO(log n + k) on average, O(n) in the worst case
SpaceO(1)

Let n be the array length and k the number of copies of target. The binary search makes at most about log2(n) + 1 probes. The two walks visit only positions that hold target, plus one stopping position each, so they cost O(k). When every value equals target, k equals n, so the total is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        lo, hi = 0, len(nums) - 1
        found = -1
        while lo <= hi:
            mid = lo + (hi - lo) // 2
            if nums[mid] == target:
                found = mid
                break
            if nums[mid] < target:
                lo = mid + 1
            else:
                hi = mid - 1
        if found == -1:
            return [-1, -1]
        first = found
        while first > 0 and nums[first - 1] == target:
            first -= 1
        last = found
        while last < len(nums) - 1 and nums[last + 1] == target:
            last += 1
        return [first, last]

The Find First/Last Occurrence infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Find First/Last Occurrence

Part of Binary Search Patterns

Approach 3: Two boundary searchesOptimalFind First/Last Occurrence

What's slow: the walk still touches every copy of target. With 10^5 copies, the walk alone costs 10^5 steps. The insight that fixes it: both edges of the block are boundary positions in a sorted array. Each edge is the first index where a test changes from false to true, so binary search finds it directly.

The start is the first index whose value is at least target. The end is one less than the first index whose value is greater than target. For integers, the second question equals the first question asked about target + 1, so one helper answers both.

Why it is correct. The test value at least x is false for every index before the answer and true for every index after it, because the array is sorted. Each probe either moves the left edge past a false index or pulls the right edge onto a true index, so the answer is never discarded. For integers, the first index above target is the first index at least target plus one, so subtracting one gives the last copy.

Steps

  1. Write lowerBound(x) that returns the first index whose value is at least x, or n if no such index exists.
  2. Set first to lowerBound(target).
  3. If first is n or nums[first] is not target, return [-1, -1].
  4. Set last to lowerBound(target + 1) - 1.
  5. Return [first, last].

Dry run

Use nums = [5, 7, 7, 8, 8, 10] and target = 8. The helper keeps a half-open range [lo, hi), starting with lo = 0 and hi = 6.

Steplohimidnums[mid]Action
106388 is not less than 8, so hi = 3
203177 is less than 8, so lo = 2
323277 is less than 8, so lo = 3
433nonenonelo equals hi, return 3

So first = 3, and nums[3] is 8, which matches. Now compute lowerBound(9).

Steplohimidnums[mid]Action
506388 is less than 9, so lo = 4
64651010 is not less than 9, so hi = 5
745488 is less than 9, so lo = 5
855nonenonelo equals hi, return 5

So last = 5 - 1 = 4. The result is [3, 4].

For target = 6, lowerBound(6) returns 1. nums[1] is 7, so the answer is [-1, -1].

Complexity

TimeO(log n)
SpaceO(1)

Let n be the array length. Each iteration of lowerBound halves the range [lo, hi), so the helper runs about log2(n) + 1 iterations. The solution calls the helper at most twice, so the total is O(log n). The helper stores three integers, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def lower_bound(x: int) -> int:
            # First index whose value is at least x, or len(nums) if none
            lo, hi = 0, len(nums)
            while lo < hi:
                mid = lo + (hi - lo) // 2
                if nums[mid] < x:
                    lo = mid + 1
                else:
                    hi = mid
            return lo

        first = lower_bound(target)
        if first == len(nums) or nums[first] != target:
            return [-1, -1]
        # First index above target, minus one, is the last copy of target
        last = lower_bound(target + 1) - 1
        return [first, last]

Common mistakes

  • return mid the moment nums[mid] == target. This returns any copy of the value, often one in the middle of the block. Keep searching, or use the two boundary searches.
  • hi = mid - 1 inside the lower bound when nums[mid] >= x. This discards mid, which may be the first copy. Set hi = mid so the candidate stays in range.
  • lo = mid when nums[mid] < x. The range never shrinks when hi = lo + 1, and the loop runs forever. Use lo = mid + 1.
  • Returning [first, last] without checking nums[first] == target. For target = 6 in the sample array, the code returns [1, 0] instead of [-1, -1].
  • last = lowerBound(target) - 1. That computes the index before the first copy, not the last copy. The end must come from the search on target + 1.
  • mid = (lo + hi) / 2 in Java, C++ or C#. With the array bounds given here it does not overflow, but lo + (hi - lo) / 2 is the safe habit and costs nothing.

Edge cases

  • nums = [], target = 0: return [-1, -1]. The bounds check must run before any read of nums[first].
  • nums = [4], target = 4: return [0, 0]. The block has one element.
  • nums = [2, 2, 2, 2], target = 2: return [0, 3]. Every value matches, so the expanding walk visits all four positions.
  • nums = [5, 7, 7], target = 1: return [-1, -1]. The lower bound is 0, and nums[0] is 5, not 1.
  • nums = [5, 7, 7], target = 9: return [-1, -1]. The lower bound is n, so the code must check first == n first.
  • nums = [-1000000000, 0, 1000000000], target = 1000000000: return [2, 2]. Large values stay inside 32-bit range, and target + 1 does not overflow.

Follow-ups interviewers ask

How would you count how many times target appears?
Subtract the two boundaries: lowerBound(target + 1) - lowerBound(target). If target is missing, both calls return the same index, so the result is 0 without a special case. The cost stays O(log n).
What if the array is not sorted?
Binary search no longer applies, because copies of target can be spread across the array. One linear scan can record the smallest and largest index where the value appears, which costs O(n) time and O(1) extra space. Sorting a copy would lose the original indices, so it does not solve the same question.
What if the array is too large to fit in memory?
If the data sits on disk in fixed-size blocks, you can binary search over block offsets. Each probe reads one block, so the search reads O(log n) blocks. If the data is a stream you cannot seek through, scan it once and keep the first and last matching indices, which uses O(n) time and O(1) memory.

Find First and Last Position of Element in Sorted Array FAQ

What is the time complexity of Find First and Last Position of Element in Sorted Array?

The optimal solution runs in O(log n) time, where n is the array length. It makes two boundary searches, and each one halves the search range at every step. The extra space is O(1).

Why use binary search for Find First and Last Position of Element in Sorted Array?

The array is sorted, so the test 'value is at least x' changes from false to true exactly once. Binary search finds that change point in O(log n) steps. The copies of target form one block, so both of its edges are change points too.

Can Find First and Last Position of Element in Sorted Array be solved in O(1) extra space?

Yes. The two-search solution keeps only lo, hi, mid and the two answers, which is constant space. The brute force also uses O(1) space, but it takes O(n) time.

Does sorting the array first help?

No. The input is already sorted, and sorting again costs O(n log n) and loses the original indices. Use the existing order with binary search.

Why does the search keep going after it finds target?

One match only proves that target exists. The block of copies can extend left or right, and a plain binary search stops at whichever match it hits first. Narrowing toward the boundary finds the true first or last index.

Asked at

See which companies ask this — Pro

Practise it