The order that sorts
A report lists items by rank without disturbing the source rows: instead of the values, it wants their positions.
- Return the original positions (counting from zero) that would put the values in ascending order.
- When values are equal, their original-index order is kept.
sorted_index_order(values: list<int>) → list<int>
Where you start
def sorted_index_order(values: list[int]) -> list[int]:
Worked examples
| Call | Result |
|---|---|
sorted_index_order([40, 10, 30, 10]) | [1, 3, 2, 0] |
sorted_index_order([20, 10, 30, 10]) | [1, 3, 0, 2] |
sorted_index_order([1, 2, 3]) | [0, 1, 2] |
sorted_index_order([3, 2, 1]) | [2, 1, 0] |
Hint
Sort a list of the indices with a comparator that looks the values up, falling back to the index itself on a tie.
Reference solution in Python
def sorted_index_order(values: list[int]) -> list[int]:
idx = list(range(len(values)))
idx.sort(key=lambda i: (values[i], i))
return idx