Drill

ProblemsGo › data

The order that sorts

harddataSortingArraysGo

A report lists items by rank without disturbing the source rows: instead of the values, it wants their positions.

sortedIndexOrder(values: list<int>) → list<int>

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func sortedIndexOrder(values []int) []int {
	
}

Worked examples

CallResult
sortedIndexOrder([]int{40, 10, 30, 10})[]int{1, 3, 2, 0}
sortedIndexOrder([]int{20, 10, 30, 10})[]int{1, 3, 0, 2}
sortedIndexOrder([]int{1, 2, 3})[]int{0, 1, 2}
sortedIndexOrder([]int{3, 2, 1})[]int{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 Go
func sortedIndexOrder(values []int) []int {
	idx := []int{}
	for i := 0; i < len(values); i++ {
		idx = append(idx, i)
	}
	sort.SliceStable(idx, func(i, j int) bool {
		if values[idx[i]] != values[idx[j]] {
			return values[idx[i]] < values[idx[j]]
		}
		return idx[i] < idx[j]
	})
	return idx
}

The same problem in another language

More data problems in Go