Find Target Indices After Sorting Array - Problem
Find Target Indices After Sorting Array

You are given a 0-indexed integer array nums and a target element target. Your task is to find all positions where the target appears after sorting the array in non-decreasing order.

A target index is an index i such that nums[i] == target in the sorted array.

Goal: Return a list of target indices after sorting nums in ascending order. If no target indices exist, return an empty list. The returned list must be sorted in increasing order.

Example: If nums = [1,2,5,2,3] and target = 2, after sorting we get [1,2,2,3,5], so target appears at indices [1,2].

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1,2,5,2,3], target = 2
โ€บ Output: [1,2]
๐Ÿ’ก Note: After sorting, nums becomes [1,2,2,3,5]. The target 2 appears at indices 1 and 2.
example_2.py โ€” Target Not Found
$ Input: nums = [1,2,5,2,3], target = 4
โ€บ Output: []
๐Ÿ’ก Note: After sorting, nums becomes [1,2,2,3,5]. The target 4 does not appear in the array, so return empty list.
example_3.py โ€” Single Element
$ Input: nums = [1], target = 1
โ€บ Output: [0]
๐Ÿ’ก Note: The array has only one element equal to target, so it appears at index 0 after sorting.

Constraints

  • 1 โ‰ค nums.length โ‰ค 100
  • 1 โ‰ค nums[i] โ‰ค 100
  • 1 โ‰ค target โ‰ค 100

Visualization

Tap to expand
๐Ÿ“š Library Book OrganizationUnsorted Books:BookID: 1BookID: 2BookID: 5BookID: 2BookID: 3Target: ID = 2๐Ÿ“Š Counting Phase:Books with ID < 2: 1 bookBooks with ID = 2: 2 booksStarting position: 1Target positions: [1, 2]Sorted Shelf (Conceptual):BookID: 1Pos: 0BookID: 2Pos: 1 โœ“BookID: 2Pos: 2 โœ“BookID: 3Pos: 3BookID: 5Pos: 4โœ… Result Found!Without actually sorting, we calculatedthat target ID 2 appears at positions:[1, 2]๐Ÿ’ก Key Insight: Position in sorted array = (count of smaller elements) + offset
Understanding the Visualization
1
Count Books
Count how many books have smaller IDs and how many match target ID
2
Calculate Positions
Books with smaller IDs come first, followed by target books
3
Generate Result
Create consecutive positions starting from the calculated starting point
Key Takeaway
๐ŸŽฏ Key Insight: The position of target elements in a sorted array can be calculated mathematically by counting smaller and equal elements, eliminating the need for actual sorting!
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
23.4K Views
Medium Frequency
~15 min Avg. Time
847 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