Find Target Indices After Sorting Array
EasyUpdated: Aug 2, 2025
Practice on:
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 sortingnums
innon-decreasing order. If there are no target indices, return anempty list. The returned list must be sorted in increasing order.
Examples
Example 1
Input: nums = [1,2,5,2,3], target = 2
Output: [1,2]
Explanation: After sorting, nums is [1,_**2**_ ,_**2**_ ,3,5].
The indices where nums[i] == 2 are 1 and 2.
Example 2
Input: nums = [1,2,5,2,3], target = 3
Output: [3]
Explanation: After sorting, nums is [1,2,2,_**3**_ ,5].
The index where nums[i] == 3 is 3.
Example 3
Input: nums = [1,2,5,2,3], target = 5
Output: [4]
Explanation: After sorting, nums is [1,2,2,3,_**5**_].
The index where nums[i] == 5 is 4.
Constraints
1 <= nums.length <= 1001 <= nums[i], target <= 100
Solution
Method 1 – Sorting and Linear Scan
Intuition
Sort the array, then collect the indices where the value equals the target. This is direct and leverages the fact that the output must be sorted.
Approach
- Sort the input array.
- Iterate through the sorted array.
- For each index, if the value equals the target, add the index to the answer list.
- Return the answer list.
Code
C++
class Solution {
public:
vector<int> targetIndices(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
vector<int> ans;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == target) ans.push_back(i);
}
return ans;
}
};
Go
func targetIndices(nums []int, target int) []int {
sort.Ints(nums)
ans := []int{}
for i, v := range nums {
if v == target {
ans = append(ans, i)
}
}
return ans
}
Java
class Solution {
public List<Integer> targetIndices(int[] nums, int target) {
Arrays.sort(nums);
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < nums.length; ++i) {
if (nums[i] == target) ans.add(i);
}
return ans;
}
}
Kotlin
class Solution {
fun targetIndices(nums: IntArray, target: Int): List<Int> {
nums.sort()
val ans = mutableListOf<Int>()
for (i in nums.indices) {
if (nums[i] == target) ans.add(i)
}
return ans
}
}
Python
class Solution:
def targetIndices(self, nums: list[int], target: int) -> list[int]:
nums.sort()
ans = []
for i, v in enumerate(nums):
if v == target:
ans.append(i)
return ans
Rust
impl Solution {
pub fn target_indices(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut nums = nums;
nums.sort();
let mut ans = vec![];
for (i, &v) in nums.iter().enumerate() {
if v == target {
ans.push(i as i32);
}
}
ans
}
}
TypeScript
class Solution {
targetIndices(nums: number[], target: number): number[] {
nums.sort((a, b) => a - b);
const ans: number[] = [];
for (let i = 0; i < nums.length; ++i) {
if (nums[i] === target) ans.push(i);
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(n log n), due to sorting the array. - 🧺 Space complexity:
O(n), for the output list.