Relative Ranks using Python

The problem of relative ranks is a popular coding interview question. Here you will be given an array of integers representing the scores of athletes, assuming that the athletes with the 1st rank will have the highest score, and you need to return an array with the ranks of athletes according to their scores. So, if you want to know how to solve this problem, this article is for you. In this article, I’ll take you through how to solve the relative ranks problem using Python.

Relative Ranks Problem

In the relative ranks problem, you will be given an array of integers representing the scores of athletes, and we need to assign ranks in descending order. The highest score will get the rank of “Gold Medal”, the second-highest score will get the rank of “Silver Medal”, the third-highest will get “Bronze Medal”, and the remaining scores will be ranked in descending order. For example, look at the input and output values of this problem shown below:

  • Input: [5, 4, 3, 2, 1] | Output: [“Gold Medal”, “Silver Medal”, “Bronze Medal”, “4”, “5”]

Relative Ranks using Python

I hope you have now understood what the problem of relative ranks means. Below is how you can solve this problem using the Python programming language:

def findRelativeRanks(scores):
    sorted_nums = sorted(scores, reverse = True)
    ranks = {}
    for i, j in enumerate(sorted_nums):
        if i == 0:
            ranks[j] = "Gold Medal"
        elif i == 1:
            ranks[j] = "Silver Medal"
        elif i == 2:
            ranks[j] = "Bronze Medal"
        else:
            ranks[j] = str(i + 1)
    return [ranks[j] for j in scores]

scores = [5,4,3,2,1]
print(findRelativeRanks(scores))
Output: ['Gold Medal', 'Silver Medal', 'Bronze Medal', '4', '5']

So this is how you can solve the relative ranks problem using Python. You can find many more practice questions for coding interviews solved and explained using Python here.

Summary

In the relative ranks problem, you will be given an array of integers representing the scores of athletes, and we need to assign ranks in descending order. The highest score will get the rank of “Gold Medal”, the second-highest score will get the rank of “Silver Medal”, the third-highest will get “Bronze Medal”, and the remaining scores will be ranked in descending order. I hope you liked this article on solving the relative ranks problem using Python. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1500

Leave a Reply