Similar Problems

Similar Problems not available

Relative Ranks - Leetcode Solution

Companies:

LeetCode:  Relative Ranks Leetcode Solution

Difficulty: Easy

Topics: sorting heap-priority-queue array  

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-100th place athletes, their rank is their placement number (i.e., the 4th place athlete's rank is "4th"). For the 101st-1000th place athletes, their rank is their placement number with the suffix "th" (i.e., the 101st place athlete's rank is "101st"). 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","4th","5th"] Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th]. Example 2:

Input: score = [10,3,8,9,4] Output: ["Gold Medal","5th","Bronze Medal","Silver Medal","4th"] Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].

Solution:

To solve this problem, we need to first sort the array of scores in descending order. This will give us the ranking of each athlete based on their score. Then we can iterate through the sorted array and assign ranks to each athlete based on their position in the sorted array.

To assign the rank, we can use a switch case statement to check the position of the athlete and assign the appropriate rank. We can also use a map to store the rank suffixes for positions beyond 3.

Here is the Python code for the solution:

class Solution: def findRelativeRanks(self, score: List[int]) -> List[str]: # Sort the scores in descending order ranks = sorted(score, reverse=True) # Create a map to store the rank suffixes suffix = {1: "Gold Medal", 2: "Silver Medal", 3: "Bronze Medal"} for i in range(3, len(score)): suffix[i+1] = str(i+1) + "th" # Assign ranks to each athlete based on their position in the sorted array for i in range(len(score)): pos = ranks.index(score[i]) if pos + 1 in suffix: score[i] = suffix[pos + 1] else: score[i] = str(pos + 1) + "th" return score

Time Complexity:

The time complexity of this solution is O(n log n), where n is the size of the input array. The sorting operation takes O(n log n) time and the iteration over the array takes O(n) time.

Space Complexity:

The space complexity of this solution is O(n), where n is the size of the input array. The space is used to store the sorted array of scores and the map of rank suffixes.

Relative Ranks Solution Code

1