Relative Ranks

Relative Ranks

You are given an integer array score of size n, where score[i] is the score of the i<sup>th</sup> athlete in a competition. All the scores are guaranteed to be unique.

The athletes are placed based on their scores, where the 1<sup>st</sup> place athlete has the highest score, the 2<sup>nd</sup> place athlete has the 2<sup>nd</sup> highest score, and so on. The placement of each athlete determines their rank:

  • The 1<sup>st</sup> place athlete's rank is "Gold Medal".

  • The 2<sup>nd</sup> place athlete's rank is "Silver Medal".

  • The 3<sup>rd</sup> place athlete's rank is "Bronze Medal".

  • For the 4<sup>th</sup> place to the n<sup>th</sup> place athlete, their rank is their placement number (i.e., the x<sup>th</sup> place athlete's rank is "x").

Return an array answer of size n where answer[i] is the rank of the i<sup>th</sup> athlete.

LeetCode Problem - 506

class Solution {
    // Method to find relative ranks based on scores
    public String[] findRelativeRanks(int[] score) {
        // Medal names for the first three ranks
        String first = "Gold Medal", second = "Silver Medal", third = "Bronze Medal";

        // Array to store the result
        String[] ans = new String[score.length];
        // Priority queue to store scores in descending order
        PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());

        // Add all scores to the priority queue
        for (int e : score) {
            pq.add(e);
        }

        // Index to track the rank
        int idx = 1;
        // Iterate through the priority queue
        while (!pq.isEmpty()) {
            // Get the highest score
            int temp = pq.poll();

            // Iterate through the original scores array
            for (int i = 0; i < score.length; i++) {
                // Assign the rank based on the score
                if (temp == score[i] && idx == 1) {
                    ans[i] = first;
                    idx++;
                    break;
                } else if (temp == score[i] && idx == 2) {
                    ans[i] = second;
                    idx++;
                    break;
                } else if (temp == score[i] && idx == 3) {
                    ans[i] = third;
                    idx++;
                    break;
                } else if (temp == score[i]) {
                    ans[i] = String.valueOf(idx);
                    idx++;
                    break;
                }
            }
        }
        // Return the result array
        return ans;
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!