Search~15 min2s · 256 MBtarget O(n) time, O(n) spacesorting
A search app asks human raters to give each result a relevance grade, a whole number from 0 to 100. The results page must list the results from the highest grade to the lowest.
Results with the same grade keep the order in which the search engine returned them. Your team lead says: "Give me the positions of the results in page order, not the grades. The grades are small whole numbers, so counting is enough."
Write order_by_grade(grades).
grades[i] is the grade of the result at position i, counting from 0.0 to n - 1 in page order: highest grade first.Input: grades = [3, 9, 3, 7, 9, 0]
Output: [1, 4, 3, 0, 2, 5]There are six results. Grade 9 comes first at positions 1 and 4, in that order. Then grade 7 at position 3, grade 3 at positions 0 and 2, and grade 0 at position 5.
| Position | Grade | Place on the page |
|---|---|---|
| 0 | 3 | 3 |
| 1 | 9 | 0 |
| 2 | 3 | 4 |
| 3 | 7 | 2 |
| 4 | 9 | 1 |
| 5 | 0 | 5 |
The start places, from the highest grade down, are 0 for grade 9, 2 for grade 7, 3 for grade 3 and 5 for grade 0.
Input: grades = [5, 5, 5]
Output: [0, 1, 2]Equal grades keep their order, so the positions stay as they are.
Input: grades = []
Output: []There are no results, so the answer is an empty list.
0 ≤ grades.length ≤ 100,000 (results)0 ≤ grades[i] ≤ 100 (relevance grade)Counting how many results come before each result costs about n × n steps, which is 10,000,000,000 at n = 100,000. There are only 101 grades, so counting and placing costs about 2n + 101 steps.