High Five Problem
Description
LeetCode Problem 1086.
Given a list of the scores of different students, items, where items[i] = [ID_i, score_i] represents one score from a student with ID_i, calculate each student's top five average.
Return the answer as an array of pairs result, where result[j] = [ID_j, topFiveAverage_j] represents the student with ID_j and their top five average. Sort result by ID_j in increasing 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.
Example 1:
Input: items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
Output: [[1,87],[2,88]]
Explanation:
The student with ID = 1 got scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 + 92 + 91 + 87 + 65) / 5 = 87.
The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 + 76) / 5 = 88.6, but with integer division their average converts to 88.
Example 2:
Input: items = [[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100]]
Output: [[1,100],[7,100]]
Constraints:
1 <= items.length <= 1000items[i].length == 21 <= ID_i <= 10000 <= score_i <= 100- For each
ID_i, there will be at least five scores.
Solution
Approach: Group Scores by ID and Sort
Group the scores by student. Since IDs are between 1 and 1000, an array of 1001 lists indexed by ID works, and walking that array from 1 to 1000 gives the students already in increasing order of ID. (A hash map works too, then sort its keys.)
For each student who has scores, sort them in decreasing order, add up the first five and divide by 5 with integer division. Every student has at least five scores, so there is always a top five.
Complexity: O(n log n) time for sorting the scores, where n is the length of items. O(n) space for the grouped scores. A min-heap of size 5 per student would make this O(n).
from collections import defaultdict
class Solution:
def highFive(self, items: List[List[int]]) -> List[List[int]]:
scores = defaultdict(list)
for student, score in items:
scores[student].append(score)
ans = []
for student in sorted(scores):
top5 = sorted(scores[student], reverse=True)[:5]
ans.append([student, sum(top5) // 5])
return ans