2089. Find Target Indices After Sorting Array
SourceWeekly Contest 269 Q1DifficultyEasyRating1152
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.
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
Solutions
Solution 1
Thinking
With \(n \le 100\), sort and collect indices equal to \(\textit{target}\); they already appear in increasing order.
A linear count of smaller/equal values could build the same range; the code simply sorts.
1 2 3 4 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 | |
Solution 2: Counting
Thinking
Solution 1 sorts the whole array to recover indices, so the time stays \(O(n \log n)\). Those indices depend only on where \(\textit{target}\) would sit after sorting, not on the order among the other values.
The number of values strictly less than \(\textit{target}\) is the start of that contiguous range, and the number of values equal to \(\textit{target}\) is its length. Both counts come from one pass over the original array, which removes the comparison sort.
After sorting into non-decreasing order, every value equal to \(\textit{target}\) occupies one contiguous index range. The start of the range equals the number of elements strictly less than \(\textit{target}\), and the length equals the number of elements equal to \(\textit{target}\).
Scan \(\textit{nums}\) once and store the two counts in \(\textit{less}\) and \(\textit{equal}\). The answer is every integer in \([\textit{less}, \textit{less} + \textit{equal})\). The range is empty when \(\textit{equal} = 0\).
The time complexity is \(O(n)\), and the space complexity is \(O(1)\), where \(n\) is the length of \(\textit{nums}\).
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |