LeetCode 506: Relative Ranks Solution

Master LeetCode problem 506 (Relative Ranks), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

506. Relative Ranks

Problem Explanation

Explanation

To solve this problem, we can first create a map to store the scores and their corresponding indices. Then, we can sort the scores in descending order and assign ranks accordingly. Finally, we can update the ranks in the result array based on the original indices.

  • Create a map to store scores and indices.
  • Sort scores in descending order.
  • Assign ranks based on the sorted scores.
  • Update ranks in the result array based on original indices.

Time Complexity: O(n log n) - Sorting the scores Space Complexity: O(n) - Using a map to store scores and indices

Solution Code

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

class Solution {
    public String[] findRelativeRanks(int[] score) {
        int n = score.length;
        String[] result = new String[n];
        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < n; i++) {
            map.put(score[i], i);
        }

        Arrays.sort(score);
        for (int i = 0; i < n; i++) {
            int index = map.get(score[n - i - 1]);
            if (i == 0) {
                result[index] = "Gold Medal";
            } else if (i == 1) {
                result[index] = "Silver Medal";
            } else if (i == 2) {
                result[index] = "Bronze Medal";
            } else {
                result[index] = String.valueOf(i + 1);
            }
        }

        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 506 (Relative Ranks)?

This page provides optimized solutions for LeetCode problem 506 (Relative Ranks) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 506 (Relative Ranks)?

The time complexity for LeetCode 506 (Relative Ranks) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 506 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 506 in Java, C++, or Python.

Back to LeetCode Solutions