Advertisement

Relative Ranks - LeetCode 506 Solution

Relative Ranks - Complete Solution Guide

Relative Ranks is LeetCode problem 506, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

You are given an integer array score of size n , where score[i] is the score of the i th athlete in a competition. All the scores are guaranteed to be unique . The athletes are placed based on their scores, where the 1 st place athlete has the highest score, the 2 nd place athlete has the 2 nd highest score, and so on. The placement of each athlete determines their rank: The 1 st place athlete's rank is "Gold Medal" . The 2 nd place athlete's rank is "Silver Medal" . The 3 rd place athlete's ran

Detailed Explanation

The problem asks you to rank athletes based on their scores in a competition. You are given an array `score` where `score[i]` represents the score of the i-th athlete. The task is to return an array of strings where each string represents the rank of the corresponding athlete. The top three athletes receive "Gold Medal", "Silver Medal", and "Bronze Medal", respectively. The remaining athletes receive their numerical rank (e.g., the 4th place athlete receives "4"). All scores are guaranteed to be unique.

Solution Approach

The solution involves sorting the scores while preserving the original index of each score. We then iterate through the sorted scores and assign the appropriate rank (either a medal or a numerical rank) based on the position in the sorted list. Finally, we create a result array where the index corresponds to the original athlete index and the value is their rank.

Step-by-Step Algorithm

  1. Step 1: Create a data structure (e.g., an array of pairs or tuples) to store each score along with its original index in the input array.
  2. Step 2: Sort the data structure in descending order based on the score.
  3. Step 3: Create a result array of strings with the same size as the input array. Initialize it with empty strings.
  4. Step 4: Iterate through the sorted data structure. For the first three elements, assign "Gold Medal", "Silver Medal", and "Bronze Medal" to the corresponding index in the result array.
  5. Step 5: For the remaining elements, assign their rank (position + 1) as a string to the corresponding index in the result array.
  6. Step 6: Return the result array.

Key Insights

  • Insight 1: The problem requires sorting the scores to determine the ranks.
  • Insight 2: It's crucial to maintain the original index of each score so we can assign the correct rank to each athlete.
  • Insight 3: The top 3 ranks are special string cases while the rest are numerical ranks.

Complexity Analysis

Time Complexity: O(n log n)

Space Complexity: O(n)

Topics

This problem involves: Array, Sorting, Heap (Priority Queue).

Companies

Asked at: Electronic Arts.