# Relative Ranks
**Difficulty:** EASY
[External](https://leetcode.com/problems/relative-ranks)
Canonical: https://scaleengineer.com/dsa/problems/relative-ranks
**Algorithms:** [Sorting](https://scaleengineer.com/algorithms/sorting)
**Data structures:** Array, Heap (Priority Queue)
**Companies:** [Electronic Arts](https://scaleengineer.com/companies/electronic-arts)
---
## 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 the `nth` place athlete, their rank is their placement number (i.e., the `xth` place athlete's rank is `"x"`).

Return an array `answer` of size `n` where `answer[i]` is the **rank** of the `ith` athlete.

**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].

**Constraints:**

* `n == score.length`
* `1 <= n <= 104`
* `0 <= score[i] <= 106`
* All the values in `score` are **unique**.

# Approaches
## Brute Force with Nested Loops
This is a straightforward brute-force approach. For each athlete, we iterate through all other athletes to count how many have a higher score. This count directly gives us the rank of the current athlete.
**Time:** O(n^2), where n is the number of athletes. For each athlete, we perform a linear scan of the entire score array. · **Space:** O(n) to store the result array. If the output array is not considered, the space complexity is O(1).
**Pros:** Simple to understand and implement.; Requires no extra space besides the output array.
**Cons:** Highly inefficient for larger inputs due to its quadratic time complexity.; Likely to cause a 'Time Limit Exceeded' error on most online judges for the given constraints.
### Explanation
The algorithm works by taking each score one by one and comparing it against every other score in the array. By counting how many scores are greater than the current score, we can determine its rank. For example, if zero scores are greater, the rank is 1. If one score is greater, the rank is 2, and so on. Once the numeric rank is found, it's converted to the required string format and placed in the result array at the same index as the original score.

```java
class Solution {
    public String[] findRelativeRanks(int[] score) {
        int n = score.length;
        String[] answer = new String[n];

        for (int i = 0; i < n; i++) {
            int rank = 1;
            for (int j = 0; j < n; j++) {
                if (score[j] > score[i]) {
                    rank++;
                }
            }

            if (rank == 1) {
                answer[i] = "Gold Medal";
            } else if (rank == 2) {
                answer[i] = "Silver Medal";
            } else if (rank == 3) {
                answer[i] = "Bronze Medal";
            } else {
                answer[i] = String.valueOf(rank);
            }
        }
        return answer;
    }
}
```
### Algorithm
- Create a result array `answer` of size `n`.
- Loop through each score `score[i]` in the input array.
- For each `score[i]`, initialize its `rank` to 1.
- Start a nested loop to compare `score[i]` with every other score `score[j]`.
- If `score[j]` is greater than `score[i]`, increment the `rank`.
- After the inner loop, the calculated `rank` is the placement of the athlete.
- Convert the rank number into the corresponding string ("Gold Medal", "Silver Medal", "Bronze Medal", or the number itself as a string).
- Store this rank string in `answer[i]`.
- Return the `answer` array after the outer loop finishes.

## Sorting with Index Preservation
A more efficient approach is to sort the scores. However, sorting the original array would lose the initial order of athletes. To solve this, we can store each score along with its original index in a separate data structure (like a 2D array or a list of custom objects), sort this structure based on scores, and then use the stored indices to populate the result array correctly.
**Time:** O(n log n), dominated by the sorting step. Populating the initial and final arrays takes O(n) time. · **Space:** O(n) to store the `scoreWithIndex` array or a similar data structure.
**Pros:** Significantly faster than the brute-force approach for larger inputs.; A standard and reliable method for ranking problems where original order matters.
**Cons:** Requires extra space to store the score-index pairs.
### Explanation
We first create a 2D array, `scoreWithIndex`, to store pairs of `{score, original_index}`. After populating this array, we sort it in descending order based on the scores. The sorted array now has the highest score at index 0, the second highest at index 1, and so on. We can then iterate through this sorted array. For each element at index `i`, we know its rank is `i+1`. We retrieve its original index and place the corresponding rank string ('Gold Medal', 'Silver Medal', etc.) into our final `answer` array at that original index.

```java
import java.util.Arrays;

class Solution {
    public String[] findRelativeRanks(int[] score) {
        int n = score.length;
        int[][] scoreWithIndex = new int[n][2];
        for (int i = 0; i < n; i++) {
            scoreWithIndex[i][0] = score[i];
            scoreWithIndex[i][1] = i;
        }

        // Sort in descending order based on score
        Arrays.sort(scoreWithIndex, (a, b) -> b[0] - a[0]);

        String[] answer = new String[n];
        for (int i = 0; i < n; i++) {
            int originalIndex = scoreWithIndex[i][1];
            if (i == 0) {
                answer[originalIndex] = "Gold Medal";
            } else if (i == 1) {
                answer[originalIndex] = "Silver Medal";
            } else if (i == 2) {
                answer[originalIndex] = "Bronze Medal";
            } else {
                answer[originalIndex] = String.valueOf(i + 1);
            }
        }
        return answer;
    }
}
```
An alternative with the same complexity is to use a Max-Heap (PriorityQueue) to store the `{score, index}` pairs, which naturally processes them in descending order of score.
### Algorithm
- Create a data structure to hold pairs of (score, original_index). A 2D array `int[n][2]` is a good choice.
- Populate this structure by iterating through the input `score` array: `pairs[i] = {score[i], i}`.
- Sort the `pairs` array in descending order based on the scores.
- Create a result array `answer` of size `n`.
- Iterate through the sorted `pairs` array. The element at index `i` in the sorted array corresponds to the athlete with rank `i+1`.
- For each `pair` at index `i`, get its original index, `originalIndex = pair[1]`.
- Assign the rank based on `i`: "Gold Medal" for `i=0`, "Silver Medal" for `i=1`, "Bronze Medal" for `i=2`, and `String.valueOf(i+1)` for others.
- Place the rank string into `answer[originalIndex]`.
- Return the `answer` array.

## Direct Mapping using an Array
This is the most efficient approach, which leverages the constraints on the score values (`0 <= score[i] <= 10^6`). Instead of a comparison-based sort, we can use an array as a direct map (or a hash map) to link scores to their original indices. This allows us to find the ranks in linear time.
**Time:** O(n + M), where `n` is the number of scores and `M` is the maximum score. Finding max score is O(n), populating the map is O(n), and iterating through the map is O(M). · **Space:** O(n + M), where `n` is the number of scores and `M` is the maximum score value. This is for the `scoreToIndex` mapping array and the result array.
**Pros:** Fastest possible approach with linear time complexity.; Avoids the O(n log n) overhead of comparison-based sorting.
**Cons:** Space complexity is dependent on the maximum value of the score, which could be very large in other problems.; Can be memory-intensive if the range of scores is much larger than the number of scores.
### Explanation
The core idea is similar to Counting Sort. We first find the maximum score to determine the size of a helper array, `scoreToIndex`. This array will use the score value as an index and store the original athlete's index as the value. After populating this map in O(n) time, we can iterate from the `maxScore` down to 0. When we find a valid entry in our `scoreToIndex` array, we know we've found the next highest score. We assign it the current rank, place the rank string in the final `answer` array at the correct original index, and then increment our rank counter for the next score we find.

```java
import java.util.Arrays;

class Solution {
    public String[] findRelativeRanks(int[] score) {
        int n = score.length;
        int maxScore = 0;
        for (int s : score) {
            maxScore = Math.max(maxScore, s);
        }

        // scoreToIndex[s] stores the original index of score s
        int[] scoreToIndex = new int[maxScore + 1];
        Arrays.fill(scoreToIndex, -1); // Initialize with a sentinel value
        for (int i = 0; i < n; i++) {
            scoreToIndex[score[i]] = i;
        }

        String[] answer = new String[n];
        int rank = 1;
        for (int s = maxScore; s >= 0; s--) {
            if (scoreToIndex[s] != -1) { // If score s exists
                int originalIndex = scoreToIndex[s];
                if (rank == 1) {
                    answer[originalIndex] = "Gold Medal";
                } else if (rank == 2) {
                    answer[originalIndex] = "Silver Medal";
                } else if (rank == 3) {
                    answer[originalIndex] = "Bronze Medal";
                } else {
                    answer[originalIndex] = String.valueOf(rank);
                }
                rank++;
            }
        }
        return answer;
    }
}
```
### Algorithm
- Find the maximum score (`maxScore`) in the input array.
- Create an integer array `scoreToIndex` of size `maxScore + 1`. This array will map a score to its original index. Initialize it with a sentinel value like -1.
- Iterate through the input `score` array and populate the map: `scoreToIndex[score[i]] = i`.
- Create the result array `answer` of size `n`.
- Initialize a rank counter, `rank = 1`.
- Iterate downwards from `maxScore` to `0`.
- If `scoreToIndex[s]` is not the sentinel value, it means a score `s` existed in the input.
- Retrieve its original index: `originalIndex = scoreToIndex[s]`.
- Assign the appropriate rank string based on the `rank` counter to `answer[originalIndex]`.
- Increment the `rank` counter.
- Return the `answer` array.

# Solutions
### Java

```java
class Solution {
public
  String[] findRelativeRanks(int[] score) {
    int n = score.length;
    Integer[] idx = new Integer[n];
    for (int i = 0; i < n; ++i) {
      idx[i] = i;
    }
    Arrays.sort(idx, (i1, i2)->score[i2] - score[i1]);
    String[] ans = new String[n];
    String[] top3 = new String[]{"Gold Medal", "Silver Medal", "Bronze Medal"};
    for (int i = 0; i < n; ++i) {
      ans[idx[i]] = i < 3 ? top3[i] : String.valueOf(i + 1);
    }
    return ans;
  }
}

```

### Python

```python
class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]: n = len(score) idx = list(range(n)) idx . sort(key=lambda x: - score[x]) top3 = ['Gold Medal', 'Silver Medal', 'Bronze Medal'] ans = [None] * n for i in range(n): ans[idx[i]] = top3[i] if i < 3 else str(i + 1) return ans

```

### CPP

```cpp
class Solution {
public:
  vector<string> findRelativeRanks(vector<int> &score) {
    int n = score.size();
    vector<pair<int, int>> idx;
    for (int i = 0; i < n; ++i)
      idx.push_back(make_pair(score[i], i));
    sort(idx.begin(), idx.end(),
         [&](const pair<int, int> &x, const pair<int, int> &y) {
           return x.first > y.first;
         });
    vector<string> ans(n);
    vector<string> top3 = {"Gold Medal", "Silver Medal", "Bronze Medal"};
    for (int i = 0; i < n; ++i)
      ans[idx[i].second] = i < 3 ? top3[i] : to_string(i + 1);
    return ans;
  }
};

```
