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
1st
place athlete’s rank is"Gold Medal"
. - The
2nd
place athlete’s rank is"Silver Medal"
. - The
3rd
place athlete’s rank is"Bronze Medal"
. - For the
4th
place to thenth
place athlete, their rank is their placement number (i.e., thexth
place 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:
Input: score = [5,4,3,2,1]
Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].
Example 2:
Input: score = [10,3,8,9,4]
Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].
Solution
Video explanation
Here is the video explaining below methods in detail. Please check it out:
Method 1 - Sorting value and index
Code
Java
public String[] findRelativeRanks(int[] score) {
int n = score.length;
int[][] pair = new int[n][2];
for (int i = 0; i < n; i++) {
pair[i][0] = score[i];
pair[i][1] = i;
}
Arrays.sort(pair, (a, b) -> b[0] - a[0]);
String[] ans = new String[n];
for (int i = 0; i < n; i++) {
int idx = pair[i][1];
if (i == 0) {
ans[idx] = "Gold Medal";
} else if (i == 1) {
ans[idx] = "Silver Medal";
} else if (i == 2) {
ans[idx] = "Bronze Medal";
} else {
ans[idx] = (i+1) + "";
}
}
return ans;
}
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.
Java
public String[] findRelativeRanks(int[] score) {
int n = score.length;
PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a,b) -> score[b] - score[a]);
for (int i = 0; i < n; i++) {
pq.add(i);
}
int i = 1;
String[] ans = new String[n];
while(!pq.isEmpty()) {
int idx = pq.poll();
if (i == 1) {
ans[idx] = "Gold Medal";
} else if (i == 2) {
ans[idx] = "Silver Medal";
} else if (i == 3) {
ans[idx] = "Bronze Medal";
} else {
ans[idx] = "" + i;
}
i++;
}
return ans;
}
Complexity
- ⏰ Time complexity:
O(n log n)
-n
elements are polled from queue, and each polling takeslog n
time. - 🧺 Space complexity:
O(n)
for storing values in heap.