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

Number: 2210

Difficulty: Easy

Paid? No

Companies: TikTok, Google


Problem Description

Given a 0-indexed integer array nums and a target value, return a list of all indices where the target appears after sorting the array in non-decreasing order. If the target does not appear in the array, return an empty list.


Key Insights

  • The problem requires sorting the array first.
  • After sorting, the indices where the target resides must be collected.
  • The constraints are small (array length up to 100), so a simple sort and linear scan is efficient.
  • Edge case: if the target does not exist in the array, return an empty list.

Space and Time Complexity

Time Complexity: O(n log n) due to the sorting step. Space Complexity: O(n) for storing the sorted array (if not sorted in-place) and the list of target indices.


Solution

The solution approach involves first sorting the given array in non-decreasing order. Once sorted, iterate through the array and whenever a value equals the target, store its index in the results list. Finally, return the list of collected indices. We use an array (or list) to accumulate the indices. The sort step is the dominant cost in terms of time complexity. The solution is straightforward and leverages built-in sorting capabilities.


Code Solutions

# Sort the array and then iterate to collect indices where the value equals the target.
def targetIndices(nums, target):
    # Sort the list in non-decreasing order
    nums.sort()
    # Initialize an empty list to store target indices
    target_indices = []
    # Iterate through the sorted array
    for index, value in enumerate(nums):
        # Check if the current element equals the target
        if value == target:
            target_indices.append(index)  # Append the index to the results list
    # Return the list of target indices
    return target_indices

# Example usage
nums = [1, 2, 5, 2, 3]
target = 2
print(targetIndices(nums, target))  # Output: [1, 2]
← Back to All Questions