Find Target Indices After Sorting Array — LeetCode 2089 Python Solution
EasyArrayBinary SearchSorting
- Problem
- #2089
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums and a target element target. A target index is an index i such that nums[i] == target.
Example
- Input
- nums = [1,2,5,2,3], target = 2
- Output
- [1,2]
- Explanation
- After sorting, nums is [1,2,2,3,5].
Python solution
Python
class Solution:
def targetIndices(self, nums: List[int], target: int) -> List[int]:
nums.sort()
return [i for i, v in enumerate(nums) if v == target]Complexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 2089. Find Target Indices After Sorting 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
Frequently asked questions
- How hard is LeetCode 2089. Find Target Indices After Sorting Array?
- LeetCode 2089. Find Target Indices After Sorting Array is rated Easy on LeetCode.
- What topics does LeetCode 2089. Find Target Indices After Sorting Array cover?
- LeetCode 2089. Find Target Indices After Sorting Array is tagged Array, Binary Search and Sorting on LeetCode.