Sponsored
Sponsored
The idea is to sort the scores but preserve their original indices by pairing each score with its index. Once sorted, we can easily determine their ranks by iterating over the sorted list. We then assign the corresponding rank values based on their positions (i.e., 'Gold Medal' for the first position, etc.). This approach utilizes additional space to maintain the original indices while sorting the scores.
Time Complexity: O(n log n), where n is the number of scores, for the sorting operation.
Space Complexity: O(n) for storing the pair struct array and the result array.
1var findRelativeRanks = function(score) {
2 let scoreIndex = score.map((s, i) => [s, i]);
3 scoreIndex.sort((a, b) => b[0] - a[0]);
4
5 const medals = ["Gold Medal", "Silver Medal", "Bronze Medal"];
6 let result = new Array(score.length);
7
8 for (let i = 0; i < scoreIndex.length; i++) {
9 if (i < 3) {
10 result[scoreIndex[i][1]] = medals[i];
11 } else {
12 result[scoreIndex[i][1]] = (i + 1).toString();
13 }
14 }
15
16 return result;
17};
18
The JavaScript solution utilizes map
to construct an array of score and index pairs, which is then sorted in descending order using the sort
function. Ranks, including medals for the top scores, are assigned based on this sorted order back into the result array.
In this approach, we employ a hash map (or dictionary) to map each score to its ranking position in a sorted list. The scores are first sorted to determine order-based ranks. We then iterate through original scores, using the map to quickly assign the appropriate ranking (medal or numeric) to each score.
Time Complexity: O(n log n) from sorting.
Space Complexity: O(n) due to storage of the sorted copy.
1
In Java, we map ranks by using a dictionary (hash map) associated with each score, assigned from a sorted array of scores. This allows for quick retrieval of each score's rank, which then determines the appropriate medal or numeric rank placed in the result.