HomeLeetcode506. Relative Ranks - Leetcode Solutions

506. Relative Ranks – Leetcode Solutions

Description:

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.

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 in Python:

Python
from typing import List

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        # Create a list of tuples where each tuple contains (score, index)
        score_index_pairs = [(s, i) for i, s in enumerate(score)]
        
        # Sort the list of tuples by the score in descending order
        score_index_pairs.sort(reverse=True, key=lambda x: x[0])
        
        # Prepare an array to hold the ranks, initialized with empty strings
        n = len(score)
        ranks = [""] * n
        
        # Define the special ranks for the top 3 positions
        special_ranks = ["Gold Medal", "Silver Medal", "Bronze Medal"]
        
        # Assign ranks to the athletes based on their sorted positions
        for rank, (s, i) in enumerate(score_index_pairs):
            if rank < 3:
                # For the first three ranks, assign the special titles
                ranks[i] = special_ranks[rank]
            else:
                # For other ranks, assign their position number as string (rank+1 because rank is 0-based)
                ranks[i] = str(rank + 1)
        
        return ranks

Explanation:

  1. Step 1: Create a list of tuples, score_index_pairs, where each tuple contains the score and its index from the original list.
    • This helps in keeping track of the original positions after sorting.
  2. Step 2: Sort the list of tuples by the scores in descending order.
    • We use the sort method with reverse=True and a lambda function to sort by the first element of the tuple (the score).
  3. Step 3: Initialize an array ranks with empty strings, of the same length as score.
    • This array will store the final ranks.
  4. Step 4: Define the special ranks for the top three athletes.
  5. Step 5: Iterate through the sorted list and assign ranks based on their positions.
    • For the first three athletes, assign the special titles.For the others, assign their numeric rank as a string.
  6. Step 6: Return the ranks array.

Solution in Javascript:

JavaScript
/**
 * @param {number[]} score
 * @return {string[]}
 */
var findRelativeRanks = function(score) {
    // Step 1: Create an array of tuples where each tuple contains (score, index)
    let scoreIndexPairs = score.map((s, i) => [s, i]);
    
    // Step 2: Sort the array of tuples by the score in descending order
    scoreIndexPairs.sort((a, b) => b[0] - a[0]);
    
    // Step 3: Prepare an array to hold the ranks, initialized with empty strings
    let n = score.length;
    let ranks = new Array(n).fill("");
    
    // Step 4: Define the special ranks for the top 3 positions
    let specialRanks = ["Gold Medal", "Silver Medal", "Bronze Medal"];
    
    // Step 5: Assign ranks to the athletes based on their sorted positions
    scoreIndexPairs.forEach((pair, rank) => {
        let index = pair[1];
        if (rank < 3) {
            // For the first three ranks, assign the special titles
            ranks[index] = specialRanks[rank];
        } else {
            // For other ranks, assign their position number as string (rank + 1 because rank is 0-based)
            ranks[index] = (rank + 1).toString();
        }
    });
    
    // Step 6: Return the ranks array
    return ranks;
};

Solution in Java:

Java
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

class Solution {
    public String[] findRelativeRanks(int[] score) {
        // Step 1: Create an array of pairs where each pair contains (score, index)
        int n = score.length;
        int[][] scoreIndexPairs = new int[n][2];
        
        for (int i = 0; i < n; i++) {
            scoreIndexPairs[i][0] = score[i];
            scoreIndexPairs[i][1] = i;
        }
        
        // Step 2: Sort the array of pairs by the score in descending order
        Arrays.sort(scoreIndexPairs, (a, b) -> b[0] - a[0]);
        
        // Step 3: Prepare an array to hold the ranks
        String[] ranks = new String[n];
        
        // Step 4: Define the special ranks for the top 3 positions
        String[] specialRanks = {"Gold Medal", "Silver Medal", "Bronze Medal"};
        
        // Step 5: Assign ranks to the athletes based on their sorted positions
        for (int rank = 0; rank < n; rank++) {
            int index = scoreIndexPairs[rank][1];
            if (rank < 3) {
                // For the first three ranks, assign the special titles
                ranks[index] = specialRanks[rank];
            } else {
                // For other ranks, assign their position number as string (rank + 1 because rank is 0-based)
                ranks[index] = Integer.toString(rank + 1);
            }
        }
        
        // Step 6: Return the ranks array
        return ranks;
    }
}

Solution in C#:

C#
using System;
using System.Collections.Generic;
using System.Linq;

public class Solution {
    public string[] FindRelativeRanks(int[] score) {
        // Step 1: Create a list of tuples where each tuple contains (score, index)
        int n = score.Length;
        var scoreIndexPairs = new List<(int score, int index)>();
        
        for (int i = 0; i < n; i++) {
            scoreIndexPairs.Add((score[i], i));
        }
        
        // Step 2: Sort the list of tuples by the score in descending order
        scoreIndexPairs.Sort((a, b) => b.score.CompareTo(a.score));
        
        // Step 3: Prepare an array to hold the ranks
        string[] ranks = new string[n];
        
        // Step 4: Define the special ranks for the top 3 positions
        string[] specialRanks = { "Gold Medal", "Silver Medal", "Bronze Medal" };
        
        // Step 5: Assign ranks to the athletes based on their sorted positions
        for (int rank = 0; rank < n; rank++) {
            int index = scoreIndexPairs[rank].index;
            if (rank < 3) {
                // For the first three ranks, assign the special titles
                ranks[index] = specialRanks[rank];
            } else {
                // For other ranks, assign their position number as string (rank + 1 because rank is 0-based)
                ranks[index] = (rank + 1).ToString();
            }
        }
        
        // Step 6: Return the ranks array
        return ranks;
    }
}

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular