Problem
Given a list of the scores of different students, items
, where items[i] = [IDi, scorei]
represents one score from a student with IDi
, calculate each student’s top five average.
Return the answer as an array of pairsresult
, whereresult[j] = [IDj, topFiveAveragej]
represents the student withIDj
_and theirtop five average. Sort _result
byIDj
inincreasing order.
A student’s top five average is calculated by taking the sum of their top five scores and dividing it by 5
using integer division.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= items.length <= 1000
items[i].length == 2
1 <= IDi <= 1000
0 <= scorei <= 100
- For each
IDi
, there will be at least five scores.
Solution
Method 1 – Hash Map and Min-Heap for Top Five
Intuition
For each student, we want to efficiently track their top five scores. We use a hash map from student ID to a min-heap (priority queue) of their scores. This allows us to always keep the top five scores for each student as we process the input.
Approach
- For each [id, score] in items, push score into a min-heap for that id.
- If the heap size exceeds 5, pop the smallest score (so only the top 5 remain).
- After processing all items, for each id, compute the average of the 5 scores in the heap (integer division).
- Return the result as a list of [id, avg], sorted by id.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
, where n is the number of items, due to heap operations and sorting. - 🧺 Space complexity:
O(n)
, for storing scores per student.