#2089

Find Target Indices After Sorting Array

Easy
ArrayBinary SearchSortingSortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution involves sorting the array and then using a single pass to find the indices of the target. This is efficient because we only need to sort once and can gather indices in a single traversal.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the array nums.
  2. 2Step 2: Initialize an empty list to store the target indices.
  3. 3Step 3: Iterate through the sorted array and check if each element equals the target.
  4. 4Step 4: If it does, append the current index to the list.
  5. 5Step 5: Return the list of target indices.
solution.py5 lines
1# Full working Python code
2
3def target_indices(nums, target):
4    sorted_nums = sorted(nums)
5    return [i for i, num in enumerate(sorted_nums) if num == target]

Complexity note: The time complexity is O(n log n) due to the sorting step, and the space complexity is O(n) for storing the sorted array and the indices.

  • 1Sorting is essential to find target indices efficiently.
  • 2Using a single pass after sorting can optimize the search for indices.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.