Return the indices that sort a 1-D NumPy array in ascending order
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 1-D array-like `a`, return a 1-D integer index array `idx` such that `a[idx]` is in ascending order. Return the indices, not the sorted values, and do not modify the input.
```text
Input: a = [3, 1, 2]
Output: [1, 2, 0] (the values at positions 1, 2, 0 are 1, 2, 3)
```
```hint Positions and ties
NumPy has a function that sorts and reports where each value came from. Once you have it, decide what order two equal values should come out in, and check whether the default sort promises that order.
```
### Constraints & Assumptions
- `a` is 1-D and may be a Python list or a NumPy array.
- The values can be compared with each other (all numeric, or all strings).
- The output has the same length as `a` and holds integer positions.
### Clarifying Questions to Ask
- When two values are equal, must their indices keep the order they had in the input?
- Can the input contain NaN, and if so, where should those positions go?
- Will callers index a Python list with the result, or always a NumPy array?
### What a Strong Answer Covers
- Returns a permutation of positions such that indexing the input with it gives the ascending sequence, and leaves the input unchanged.
- Says how equal values are ordered and how to guarantee that order.
- Gives the time and space cost of the approach.
- Handles edge cases such as an empty input, a Python list input and NaN values.
### Follow-up Questions
- How does `np.argsort` handle ties, and how do you make it stable?
- How would you get descending order, and what happens to ties and to unsigned integer data with each method?
- Given the index array, how would you compute the rank of each element at its original position?
Overview: Given a 1-D array, return the integer index array that puts its values in ascending order while leaving the input unchanged. It tests index-based sorting in NumPy, how equal values are ordered, and how to produce a descending order without scrambling ties.