Problem 2089

Abstract / Summary

Given an array and a target number, return the indices where the target appears after the array is sorted.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2089.py

class Solution:
    def targetIndices(self, nums: List[int], target: int) -> List[int]:
        return [ i for i, n in enumerate(sorted(nums)) if n == target ]
3 lines | 163 bytes | submitted February 7, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 78% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that receives an integer list and a target value. It returns a collection of positions where the target appears after the list has been ordered in non-decreasing order. The solution leverages Python’s built-in sorting routine and a concise comprehension to produce the result in a single expression.

Key Steps

The algorithm proceeds through three logical phases, each reflected in a fragment of the source code.

The first phase creates a sorted copy of the input sequence.

sorted_nums = sorted(nums)

The second phase pairs each element of the sorted list with its zero-based index. This is achieved by the enumerate function, which yields a sequence of (index, value) tuples.

for i, n in enumerate(sorted_nums):
    ...

The final phase filters those pairs, retaining only the indices whose associated value equals the target. The filtered indices are collected into a list by the surrounding list comprehension.

result = [i for i, n in enumerate(sorted(nums)) if n == target]

The method returns this list directly, completing the operation.

Edge Cases Handled

When the input list is empty, the sorting step yields an empty sequence, and the comprehension iterates over no elements, resulting in an empty list of indices. If the target value does not occur in the sorted collection, the conditional if n == target never succeeds, and the returned list is likewise empty. The implementation also correctly processes inputs where the target appears multiple times; each occurrence generates a distinct index, and all such indices are included in the output. Because sorting is stable, equal elements retain their relative order, ensuring that the indices correspond to the positions they would occupy in a fully sorted arrangement.

Performance Optimizations

The solution relies on Python’s highly tuned sorted function, which implements Timsort-a hybrid algorithm that exploits existing order in the data to reduce work. By delegating the ordering to this native routine, the code benefits from low-level optimizations unavailable in a manual implementation. The use of a list comprehension combines iteration, conditional testing, and list construction into a single pass, minimizing interpreter overhead compared with a multi-step loop. Additionally, enumerate supplies indices without the need for an explicit counter variable, further streamlining the operation. These choices collectively produce a compact and efficient execution path for the task at hand.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having a big box of numbered blocks. To make sense of them, the first thing to do is line them up from the smallest number to the biggest number, just like putting your toys in a neat row. Once they are all lined up, count them one by one starting from the very first block. If a block has the special target number written on it, write down which spot it is sitting in. After checking all of the blocks in the row, the list of those spot numbers shows exactly where every block with that target number is hiding.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.59 | σ = 1.19

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
muhammadfarhankt Go
shreymehul C#
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
muhammadfarhankt Go
shreymehul C#
suxrobGM C#
varunu28 Java
28 links | 17 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

5 solutions   February 7, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality