Find First and Last Position of Element in Sorted Array — LeetCode 34 Python Solution
- Problem
- #34
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(\log n), where n is the length of the array \textit{nums} |
| Space | O(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.