Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Relative Ranks

C++, Python and TypeScript solutions for Relative Ranks.

The Relative Ranks solutions are below.

Solution files

Python•relative-ranks/synced-solution.py
class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        order = sorted(range(len(score)), key=lambda i: -score[i])
        answer = [""] * len(score)
        medals = ["Gold Medal", "Silver Medal", "Bronze Medal"]

        for rank, idx in enumerate(order):
            answer[idx] = medals[rank] if rank < 3 else str(rank + 1)
        return answer
C++•relative-ranks/synced-solution.cpp
class Solution {
public:
    vector<string> findRelativeRanks(vector<int>& score) {
        vector<int> order(score.size());
        iota(order.begin(), order.end(), 0);
        sort(order.begin(), order.end(), [&](int a, int b) {
            return score[a] > score[b];
        });

        vector<string> result(score.size());
        for (int rank = 0; rank < static_cast<int>(order.size()); rank++) {
            int idx = order[rank];
            if (rank == 0) {
                result[idx] = "Gold Medal";
            } else if (rank == 1) {
                result[idx] = "Silver Medal";
            } else if (rank == 2) {
                result[idx] = "Bronze Medal";
            } else {
                result[idx] = to_string(rank + 1);
            }
        }
        return result;
    }
};
TypeScript•relative-ranks/synced-solution.ts
function findRelativeRanks(score: number[]): string[] {
    const order = score.map((_, index) => index).sort((a, b) => score[b] - score[a]);
    const result = new Array<string>(score.length);
    const medals = ["Gold Medal", "Silver Medal", "Bronze Medal"];

    for (let rank = 0; rank < order.length; rank++) {
        const idx = order[rank];
        result[idx] = rank < 3 ? medals[rank] : String(rank + 1);
    }
    return result;
}