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 ]
Difficulty
and has an acceptance rate of about 78% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Sorting
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 1331: Rank Transform of an Array
- problem 2942: Find Words Containing Character
Solved On The Same Day
- problem 2094: Finding 3-Digit Even Numbers
- problem 2096: Step-By-Step Directions From a Binary Tree Node to Another
- problem 2131: Longest Palindrome by Concatenating Two Letter Words
- problem 2155: All Divisions With the Highest Score of a Binary Array
Extra
- 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