Social feed~15 min2s · 256 MBtarget O(n log n) time, O(n) spacesorting · hashing
A social app runs a weekly quiz challenge. Each player ends with a score, and the app shows every player their rank. Players with the same score share the same rank, and the next lower score takes the rank after all of them. Two players tied for first place both have rank 1, and the next player has rank 3.
The list of scores arrives in the order the players joined. Your answer must keep that order, because the app reads it by player.
Write ranks(scores).
scores[i] is the score of player i. A higher score is better.i is 1 plus the number of players with a strictly higher score.result with result[i] the rank of player i, in the input order.Input: scores = [50, 80, 80, 20]
Output: [3, 1, 1, 4]| Player | Score | Players with a higher score | Rank |
|---|---|---|---|
| 0 | 50 | 2 (the two 80s) | 3 |
| 1 | 80 | 0 | 1 |
| 2 | 80 | 0 | 1 |
| 3 | 20 | 3 | 4 |
Rank 2 is skipped, because two players share rank 1.
Input: scores = [10, 10, 10]
Output: [1, 1, 1]All three players are tied for first.
Input: scores = [90, 70, 70, 70, 40]
Output: [1, 2, 2, 2, 5]Three players share rank 2, so the next rank is 5.
1 ≤ scores.length ≤ 100,000 (players in the challenge)0 ≤ scores[i] ≤ 1,000,000,000 (scores)Counting the higher scores for every player takes about n × n = 10^10 steps at n = 100,000. That is too slow. Sorting the scores once costs about n log n, which is under 2 × 10^6 steps.