← All solutions
October 19Easy

Find target indices after sorting array

  • Array
  • Binary Search
  • Sorting

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.

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.

Solution

class Solution:
    def targetIndices(self, nums: list[int], target: int) -> list[int]:
        ans = []
        smaller = 0
        for num in nums:
            if num == target:
                ans.append(len(ans))
            elif num < target:
                smaller += 1
        return [i + smaller for i in ans]