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.
1def findRelativeRanks(score):
2 score_index = [(s, i) for i, s in enumerate(score)]
3 score_index.sort(reverse=True, key=lambda x: x[0])
4
5 n = len(score)
6 result = [''] * n
7 medals = ["Gold Medal", "Silver Medal", "Bronze Medal"]
8
9 for i, (s, idx) in enumerate(score_index):
10 if i < 3:
11 result[idx] = medals[i]
12 else:
13 result[idx] = str(i + 1)
14
15 return result
16
Python uses list comprehension to pair scores with their indices and sorts this list in descending order. We use enumerate
while sorting to easily track original indices. After sorting, ranks are assigned based on sorted positions with appropriate conversion for top three scores.
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
This C solution sorts a copy of the original list and uses the sorted positions to determine ranks. The qsort
function provides a sorted view, and scores are ranked by finding their positions in this sorted list. Medals are assigned for the top three ranks using conditional checks.