Problem
You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.
The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:
- The
1stplace athlete’s rank is"Gold Medal". - The
2ndplace athlete’s rank is"Silver Medal". - The
3rdplace athlete’s rank is"Bronze Medal". - For the
4thplace to thenthplace athlete, their rank is their placement number (i.e., thexthplace athlete’s rank is"x").
Return an array answer of size n where answer[i] is the rank of the ith athlete.
Examples
Example 1:
| |
Example 2:
| |
Solutions
Video explanation
Here is the video explaining below methods in detail. Please check it out:
Method 1 - Sorting value and index
Code
| |
Complexity
- ⏰ Time complexity:
O(nlogn)- sorting the array - 🧺 Space complexity:
O(n)
Method 2 - Using Priority Queue OR Max Heap
Create the max heap, add the array index to priority queue, and use the comparator on array[idx]. Now, we start polling value from the heap, getting the max value, till we empty the queue.
Code
| |
Complexity
- ⏰ Time complexity:
O(n log n)-nelements are polled from queue, and each polling takeslog ntime. - 🧺 Space complexity:
O(n)for storing values in heap.