Sponsored
This approach involves sorting the scores in descending order, then iteratively assigning ranks to each score while handling ties appropriately. This can be efficiently achieved using a sorting algorithm followed by a traversal to assign ranks. By maintaining an index while sorting, we can assign ranks directly to the original scores.
Time Complexity: O(n log n) due to the sorting operation.
Space Complexity: O(1), only a fixed amount of additional memory is used for sorting.
1class ScoreEntry:
2 def __init__(self, id, score):
3 self.id = id
4 self.score = score
5
6scores = [
7 ScoreEntry(1, 3.50),
8 ScoreEntry(2, 3.65),
9 ScoreEntry(3, 4.00),
10 ScoreEntry(4, 3.85),
11 ScoreEntry(5, 4.00),
12 ScoreEntry(6, 3.65)
13]
14
15scores.sort(key=lambda x: x.score, reverse=True)
16
17rank = 1
18for i in range(len(scores)):
19 if i == 0 or scores[i].score != scores[i - 1].score:
20 rank = i + 1
21 print(f"Score: {scores[i].score}, Rank: {rank}")
The Python solution leverages sorting with a custom key to arrange the scores in descending order. The implementation manages ranks during a single pass after sorting. Python's dynamic typing and list sequences make handling and printing straightforward.
This approach uses a bucket sort strategy, particularly efficient when scores have a limited range of decimal places. This reduces the complexity substantially in scenarios where HTTP (High Throughput Processing) is required. Counting occurrences of each score allows direct assignment of ranks in descending order of scores efficiently.
Time Complexity: O(n + k), where n is the number of scores, and k is the number of buckets (constant in this case).
Space Complexity: O(k), which is fixed and depends on BUCKET_COUNT.
1
The C bucket sort implementation converts each score based on its proximity to MIN_SCORE using a defined bucket size. Each score increments its corresponding bucket to count occurrences. The ranks are assigned by iteratively checking non-empty buckets from highest to lowest.