Relative Ranks

Updated on 23 June, 2025
Relative Ranks header image

Problem Statement

In this problem, you are provided with an integer array score where each element score[i] represents the score of the i-th athlete in a competition. The length of the array score is denoted as n. Each score within the array is unique, ensuring no ties between athletes. Athletes are ranked based on their scores, where the athlete with the highest score receives the highest rank, the second highest score gets the second rank, and so forth.

The ranking system translates scores into specific medals or placement numbers:

  • The highest score is rewarded with the "Gold Medal."
  • The second highest score receives the "Silver Medal."
  • The third highest score is awarded the "Bronze Medal."
  • From the fourth highest score onwards, the athletes' ranks are represented by their ordinal numbers, e.g., 4th, 5th, etc.

The final output is an array answer where answer[i] provides the rank or medal associated with the i-th athlete according to their score.

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

Constraints

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

Approach and Intuition

To solve this ranking problem effectively, consider the following logical steps:

  1. Sorting and Ranking:

    • Start by creating a reference to each score's original position because you need to return the rank in the order of the original scores.
    • Sort the scores in descending order so the highest scores come first. This approach helps directly in assigning the top three medals and subsequent numeric ranks.
  2. Medal Assignment:

    • Iterate through the sorted list:
      • Assign "Gold Medal" to the highest score.
      • Assign "Silver Medal" to the second highest.
      • Assign "Bronze Medal" to the third highest.
      • For all other positions, convert the rank (1-based index of the sorted array) to a string and assign accordingly.
  3. Reconstructing the Result:

    • Since sorting disrupts the order of elements, use the stored indices from the original array to place the ranks back in their corresponding positions.

Using this approach, you ensure efficiency and clarity in the formation of results, adhering to the unique conditions as stipulated by the rankings. This model effectively combines sorting, enumeration, and conditional logic to generate the desired outcome, which is both intuitive and straightforward under the constraints provided.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
private:
    int getMax(vector<int>& nums) {
        int highest = 0;
        for (int value : nums) {
            if (value > highest) {
                highest = value;
            }
        }
        return highest;
    }
public:
    vector<string> assignRanks(vector<int>& nums) {
        int total = nums.size();

        // Map each score with its index plus one to avoid confusion with zero indexing
        int highestValue = getMax(nums);
        vector<int> indexMap(highestValue + 1, 0);
        for (int i = 0; i < total; i++) {
            indexMap[nums[i]] = i + 1;
        }

        const vector<string> AWARDS = {"Gold Medal", "Silver Medal", "Bronze Medal"};

        // Sort and assign medals or ranks
        vector<string> results(total);
        int ranking = 1;
        for (int i = highestValue; i >= 0; i--) {
            if (indexMap[i] != 0) {
                int originalIdx = indexMap[i] - 1;
                if (ranking <= 3) {
                    results[originalIdx] = AWARDS[ranking - 1];
                } else {
                    results[originalIdx] = to_string(ranking);
                }
                ranking++;
            }
        }
        return results;
    }
};

The program in C++ aims to assign ranks to athletes based on their scores. It accepts an array of integer scores and returns a vector of strings representing each athlete's rank.

  • Initialize a getMax function to identify the highest score in the provided list of scores.
  • In the assignRanks function:
    • Determine the size of the input nums.
    • Create a mapped array (indexMap) using the highest score to maintain a relationship between scores and their original indices, offset by one to manage zero indexing gracefully.
    • Define medals for the top three ranks using a constant vector AWARDS.
    • Initialize a results vector to store the final ranking or medals for each athlete.
    • Sort the scores in descending order. For each score, determine its original index and assign the appropriate rank or medal based on its position:
      • The top three athletes receive "Gold Medal", "Silver Medal", and "Bronze Medal" respectively.
      • Other athletes receive ranks starting from 4 onwards, represented as string numbers.

This solution efficiently maps scores to their original positions and sorts them to assign ranks, ensuring a clear and accurate rank assignment for any list of scores.

java
class Solution {
    private int getMaxScore(int[] scores) {
        int max = 0;
        for (int s : scores) {
            if (s > max) {
                max = s;
            }
        }
        return max;
    }

    public String[] assignRanks(int[] scores) {
        int totalScores = scores.length;
        
        int maximum = getMaxScore(scores);
        int[] indexByScore = new int[maximum + 1];
        
        for (int i = 0; i < totalScores; i++) {
            indexByScore[scores[i]] = i + 1;
        }

        final String[] TOP_MEDALS = {"Gold Medal", "Silver Medal", "Bronze Medal"};
        
        String[] ranks = new String[totalScores];
        int rankPosition = 1;
        
        for (int i = maximum; i >= 0; i--) {
            if (indexByScore[i] != 0) {
                int oriIndex = indexByScore[i] - 1;
                
                if (rankPosition < 4) {
                    ranks[oriIndex] = TOP_MEDALS[rankPosition - 1];
                } else {
                    ranks[oriIndex] = String.valueOf(rankPosition);
                }
                rankPosition++;
            }
        }
        return ranks;
    }
}

The given Java solution solves the problem of assigning medals and ranking positions to athletes based on their scores. The code comprises two primary functions within the Solution class, designed to efficiently map scores to their relative ranks. Here's a concise explanation of the process:

  1. Determine the Maximum Score: The method getMaxScore() traverses an array of scores to find the highest value. This value helps in setting up an array to index scores for rank assignment.

  2. Assign Ranks to Scores: The assignRanks() method initializes an array indexByScore with a length determined by the maximum score. This array is used to track positions of scores originally in the list. Each score directly maps to an index in this auxiliary array, pointing to their original position in the input list but incremented by one to handle zero-index adjustments.

  3. Mapping Scores to Ranks: The core of the solution involves a reverse iteration from the highest possible score down to zero. During this iteration, for each score that exists (checked using indexByScore), the algorithm assigns either a medal ("Gold Medal", "Silver Medal", or "Bronze Medal") for the top three positions, or a numerical rank for other positions. This rank assignment uses another array ranks initialized to store each position's rank in String format.

  4. Output Construction: As the loop decrements from maximum score and finds actual scores (non-zero indices in indexByScore), it determines the rank based on rankPosition. If ranked within the top three, it uses predefined strings; otherwise, it converts the rank position to a string. This continues until all scores are assigned a rank.

This efficient approach leverages direct indexing by score values, ensuring a linear pass for assignments once the maximum score is identified, thereby optimizing the process significantly compared to a naive sorting approach.

python
class Solution:
    def maximum_score(self, values):
        highest = 0
        for val in values:
            if val > highest:
                highest = val
        return highest

    def assignRanks(self, scores):
        length = len(scores)

        # Track the original index with a mapped score
        highest_score = self.maximum_score(scores)
        index_map = [0] * (highest_score + 1)
        for idx in range(length):
            index_map[scores[idx]] = idx + 1

        AWARDS = ["Gold Medal", "Silver Medal", "Bronze Medal"]

        # Determine ranks based on scores
        ranking = [None] * length
        position = 1
        for score_index in range(highest_score, -1, -1):
            if index_map[score_index] != 0:
                original_idx = index_map[score_index] - 1
                if position < 4:
                    ranking[original_idx] = AWARDS[position - 1]
                else:
                    ranking[original_idx] = str(position)
                position += 1
        return ranking

The Python code provided defines a class Solution with methods for determining the relative rankings of a list of scores in sporting events. The process involves comparing athlete scores and assigning ranks such as "Gold Medal", "Silver Medal", and "Bronze Medal" to the top three performers, while others receive a rank based on their position.

Here's a breakdown of the solution:

  1. The maximum_score method iterates through a list of values to find and return the highest score.
  2. In the assignRanks method:
    • First, the highest score is identified using maximum_score.
    • An index_map array is created and initialized to keep track of the original index positions of each score.
    • A loop assigns each score's original index to the index_map where the index in index_map corresponds to the score and the value at that index represents the one-based index position of the score in the original list.
    • AWARDS array holds the medals corresponding to the top three positions.
    • Another array, ranking, is prepared to hold the final rank strings for each athlete.
    • A reverse loop from the highest score to zero assigns ranks to athletes based on their scores. If a score is found in index_map, its original position is determined and the appropriate rank (medal or numeric rank) is assigned.
    • The rankings are returned as a list, where each position corresponds to the rank of the athlete in the original list of scores.

This approach ensures that athletes are ranked in descending order of their scores, and ties are handled by the order in which scores appear (first come, first serve basis in the original list). The solution leverages direct indexing for efficient score-to-index mapping, facilitating quick rank assignments.

Comments

No comments yet.