Find First and Last Position of Element in Sorted Array — LeetCode 34 Python Solution

MediumArrayBinary Search
Problem
#34
Reading time
2 min

The problem

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

Example

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

Python solution

Python
class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        l = bisect_left(nums, target)
        r = bisect_left(nums, target + 1)
        return [-1, -1] if l == r else [l, r - 1]

Complexity

MeasureComplexity
TimeO(\log n), where n is the length of the array \textit{nums}
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 34. Find First and Last Position of Element in Sorted Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 34. Find First and Last Position of Element in Sorted Array?
LeetCode 34. Find First and Last Position of Element in Sorted Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 34. Find First and Last Position of Element in Sorted Array?
The Python solution on this page runs in O(\log n), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 34. Find First and Last Position of Element in Sorted Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 34. Find First and Last Position of Element in Sorted Array cover?
LeetCode 34. Find First and Last Position of Element in Sorted Array is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview