|
| 1 | +# Problem: Relative Ranks |
| 2 | +# Link: https://leetcode.com/problems/relative-ranks/description/ |
| 3 | +# Tags: Array, Sorting, Hash Map |
| 4 | +# Approach: Pair each score with its original index, sort by score descending, |
| 5 | +# and assign "Gold/Silver/Bronze Medal" for top three; for the rest, |
| 6 | +# assign rank numbers as strings. Place results back using original indices. |
| 7 | +# Time Complexity: O(n log n) # sorting |
| 8 | +# Space Complexity: O(n) # result array + index pairs |
| 9 | + |
| 10 | + |
| 11 | +class Solution: |
| 12 | + def findRelativeRanks(self, score): |
| 13 | + n = len(score) |
| 14 | + res = [""] * n |
| 15 | + |
| 16 | + # (score, index) pairs sorted by score descending |
| 17 | + order = sorted([(s, i) for i, s in enumerate(score)], reverse=True) |
| 18 | + |
| 19 | + for rank, (_, idx) in enumerate(order, start=1): |
| 20 | + if rank == 1: |
| 21 | + res[idx] = "Gold Medal" |
| 22 | + elif rank == 2: |
| 23 | + res[idx] = "Silver Medal" |
| 24 | + elif rank == 3: |
| 25 | + res[idx] = "Bronze Medal" |
| 26 | + else: |
| 27 | + res[idx] = str(rank) |
| 28 | + |
| 29 | + return res |
0 commit comments