Problem Description
Given a list of student scores where each element is in the form [ID, score], calculate each student's top five average. The top five average is obtained by summing the highest five scores of that student and using integer division by 5. The result should be returned as an array of pairs sorted by student ID in increasing order.
Key Insights
- Use a hash table (or dictionary/Map) to group scores by student ID.
- For each student, maintain a data structure (min-heap) to keep track of the top five scores efficiently.
- If the heap size exceeds five and a new score is greater than the smallest score, replace it.
- After processing, compute the average of the scores in the heap using integer division.
- Finally, sort the results by student ID before returning.
Space and Time Complexity
Time Complexity: O(n log k) for iterating through all scores (with k fixed at 5, this is essentially O(n)), plus O(m log m) for sorting the m student IDs.
Space Complexity: O(n) for storing the scores grouped by student IDs.
Solution
The solution groups scores by student ID using a dictionary. For each student, a min-heap (or priority queue) is used to maintain the top five scores. As scores are processed, if a student's heap has fewer than 5 scores, the new score is simply added. Once the heap contains five scores, subsequent scores are compared with the current minimum; if a new score is greater, it replaces the smallest element in the heap. After processing all scores, the sum of each student's top five scores is divided by 5 (using integer division) to get the top five average. Finally, the results are sorted by student ID and returned.