2089. Find Target Indices After Sorting Array

1 min read

LeetCode Daily Problem: Find Target Indices After Sorting Array

On this page

Original problem on LeetCode

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.

Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.

Approach

The direct solution is simple, though there is room to optimize. For example, scan once to count how many numbers are smaller than target and how many equal it, then generate the indices directly. That lowers the complexity.

python
class Solution:
    def targetIndices(self, nums: list[int], target: int) -> list[int]:
        nums.sort()
        res = []
        for i, num in enumerate(nums):
            if num == target:
                res.append(i)
        return res

Complexity

  • Time: O(n log n) — sorting dominates.
  • Space: O(n) for the output, O(1) extra.
TagsSimulation

Back to all posts