Find Target Indices After Sorting the Array

Easy

Topics
ArrayBinary SearchSorting

Given an array nums and an integer target, first sort nums in non-decreasing order. Return the list of indices i (in increasing order) such that after sorting nums[i] == target. If target is not present, return an empty list.

Example 1

1021522334
Input:  nums = [1,2,5,2,3], target = 2
Output: [1,2]

Example 2

1021522334
Input:  nums = [1,2,5,2,3], target = 3
Output: [3]

Example 3

1021522334
Input:  nums = [1,2,5,2,3], target = 5
Output: [4]

Constraints

  • 1 <= nums.length <= 100
  • 1 <= nums[i], target <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

After sorting, every copy of target sits in one contiguous block. Sorting and then scanning for that block works and costs O(n log n).

But the block's position is determined by just two counts, and neither needs a sort. The number of values strictly less than target is where the block starts; the number equal to target is how long it is. So the answer is the run of indices [lo, lo + count) — computed in two linear passes with no sorting at all.

This is the counting idea again: when the question is about positions in sorted order rather than the sorted array itself, counts are enough.

Approach

  1. lo = how many values are < target.
  2. count = how many equal target.
  3. Return [lo, lo+1, ..., lo+count-1], which is empty when count is 0.

Dry Run

nums = [1,2,5,2,3], target = 2

values < 2:  just 1          -> lo = 1
values == 2: two of them     -> count = 2
answer indices [1, 2]

check: sorted is [1,2,2,3,5]; the 2s sit at indices 1 and 2  ✓

Complexity

  • Time — O(n): two counting passes, which can trivially be one. Against O(n log n) if you actually sort.
  • Space — O(1) beyond the output list, which is the result rather than scratch space.

Common Pitfalls

  • Sorting when counting suffices. Correct but asymptotically worse, and it mutates the caller's array unless copied.
  • Counting <= for the start position. The block begins after the strictly smaller values; including equals puts it past the block.
  • Returning values instead of indices.
  • Special-casing "target absent". A count of 0 yields an empty range naturally.
  • Assuming the input is already sorted. It is not; only the answer is defined in terms of sorted order.

Full Solution — all languages

class Solution:
    def targetIndices(self, nums, target):
        lo = sum(1 for x in nums if x < target)
        cnt = sum(1 for x in nums if x == target)
        return list(range(lo, lo + cnt))
SensAI
Beta
Tap the mic to stop voice mode