We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find Target Indices After Sorting Array

Difficulty: Easy


Problem Description

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.


Key Insights

  • The problem requires sorting the array and then finding the indices of the target element.
  • Sorting is necessary to determine the order of elements, which affects the indices where the target appears.
  • We can utilize a simple approach of sorting and then iterating through the sorted array to collect indices of the target.

Space and Time Complexity

Time Complexity: O(n log n) due to the sorting step, where n is the length of nums.
Space Complexity: O(n) for storing the sorted version of the array, if we consider the space used by sorting.


Solution

To solve this problem, we will:

  1. Sort the given array nums in non-decreasing order.
  2. Iterate through the sorted array and collect the indices where the value is equal to the target.
  3. Return the list of collected indices.

We will use a list to store the indices and a sorting algorithm (like Timsort, which is used in Python) to sort the array.


Code Solutions

def targetIndices(nums, target):
    # Sort the array
    nums.sort()
    # List to store the target indices
    result = []
    # Collect indices of the target
    for i in range(len(nums)):
        if nums[i] == target:
            result.append(i)
    return result
← Back to All Questions