Find Target Indices After Sorting Array - 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,5,2,3], target = 2
Output: [1,2]
💡 Note: After sorting: [1,2,2,3,5]. Target 2 appears at indices 1 and 2.
Example 2 — No Target Found
$ Input: nums = [1,2,5,2,3], target = 4
Output: []
💡 Note: After sorting: [1,2,2,3,5]. Target 4 is not found, so return empty list.
Example 3 — Single Element
$ Input: nums = [1], target = 1
Output: [0]
💡 Note: Array has one element which matches target, so return [0].

Constraints

  • 1 ≤ nums.length ≤ 100
  • -100 ≤ nums[i] ≤ 100
  • -100 ≤ target ≤ 100

Visualization

Tap to expand
Find Target Indices After Sorting Array INPUT Original Array: nums 1 i=0 2 i=1 5 i=2 2 i=3 3 i=4 target = 2 = matches target nums = [1,2,5,2,3] target = 2 ALGORITHM STEPS 1 Count smaller Count elements < target count = 1 (only "1") 2 Count target Count elements == target targetCount = 2 3 Calculate start startIndex = count = 1 4 Generate indices From start to start+count-1 Sorted: [1,2,2,3,5] indices[0] = 1 indices[1] = 1+1 = 2 Result: [1, 2] FINAL RESULT Sorted Array: 1 i=0 2 i=1 2 i=2 3 i=3 5 i=4 Target indices found: [1, 2] OK - Found 2 indices nums[1]=2, nums[2]=2 Time: O(n) Space: O(1) Key Insight: Instead of sorting the array, count elements smaller than target to find the starting index, then count elements equal to target to determine how many consecutive indices exist. startIndex = count(nums < target), length = count(nums == target) --> indices from start to start+length-1 TutorialsPoint - Find Target Indices After Sorting Array | Count-Based Approach
Asked in
Amazon 15 Microsoft 12 Google 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen