Tensorum
LeetCode 34 · Basics / Lower & Upper Bound

Find First and Last Position of Element in Sorted Array

LeetCode 34 · Medium · solution, intuition & step-by-step walkthrough

Two biased binary searches.

MediumArrayBinary Search
0 msruntime · beats 100%
18.8 MBmemory · beats 100%
1approach
5accepted runs · last 23 Apr 2025

This is how I solved Find First and Last Position of Element in Sorted Array (LeetCode 34), a medium problem from the Basics / Lower & Upper Bound pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Run binary search twice. When you hit the target, don't stop: record it and keep searching left for the first position, or right for the last position.

Approach

  1. 1

    First: on a match, save mid and set high = mid − 1.

  2. 2

    Last: on a match, save mid and set low = mid + 1.

  3. 3

    Return [first, last] (−1 if absent).

How I solved it

Lower + upper bound searchesPythonO(log n) time
class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def getFirstPosition():
            ans=-1
            low = 0
            high=len(nums)-1
            while low<=high:
                mid = (low+high)//2
                if nums[mid]==target:
                    ans = mid
                    high = mid-1
                elif nums[mid]>target:
                    high = mid-1
                else:
                    low = mid+1
            return ans
        def getLastPosition():
            ans=-1
            low = 0
            high=len(nums)-1
            while low<=high:
                mid = (low+high)//2
                if nums[mid]==target:
                    ans = mid
                    low = mid+1
                elif nums[mid]>target:
                    high = mid-1
                else:
                    low = mid+1
            return ans
        first = getFirstPosition()
        last = getLastPosition()
        return [first,last]
Loading the step-through…

Find First and Last Position of Element in Sorted Array — FAQ

What is the intuition behind Find First and Last Position of Element in Sorted Array?

Run binary search twice. When you hit the target, don't stop: record it and keep searching left for the first position, or right for the last position.

How do you solve Find First and Last Position of Element in Sorted Array (LeetCode 34)?

1. First: on a match, save mid and set high = mid − 1. 2. Last: on a match, save mid and set low = mid + 1. 3. Return [first, last] (−1 if absent).

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

Time: O(log n). Space: O(1). (Accepted approach: Lower + upper bound searches.)

What are common mistakes in Find First and Last Position of Element in Sorted Array?

A linear scan from one hit is O(n) in the worst case.