Statementâ–¼
You are given a list of scores for multiple students, represented as items
, where
Return the result as an array of pairs, result
, where result
should be sorted in ascending order by
Note: To calculate the top five averages for each student, sum their highest five scores and perform integer division by
5 .
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
The idea is to use a hash map (dictionary) to store the scores for each student and then calculate the average of the top five scores for each student using sorting. The approach keeps track of the scores by using a dictionary where each key represents a student ID, and the corresponding value is a list of scores for that student. The solution sorts the scores for each student to find the top five, ensuring an accurate average calculation.
Now, let’s walk-through the steps of the solution:
We create a dictionary,Â
dict
, to store scores for each student ID.We create a variableÂ
max_id
, to keep track of the highest student ID encountered.We iterate through theÂ
items
 list, where each element is a pairÂ[ID,score] of a student, and for each pair:We append theÂ
score corresponding to the ID inÂdict
.We update
max_id
  to themaximum(current ID, max_id
) . We do this to keep track of the highest student ID seen.
After iterating through
items
and storing scores indict
, we initialize an empty listÂresult
 to store the final output.Next, we iterate through all possible IDs from 1 toÂ
max_id
 (inclusive) and check whether there are scores inÂdict
for each ID. If there are, we do the following:We find the top
5 scores for the current student.We calculate the average of the top
5 scores using integer division.We append the pairÂ
[ID,AverageScore] Â to theÂresult
 list.
Finally, we return
result
, which contains each student's ID and their corresponding top five average scores.
Let’s look at the following illustration to get a better understanding of the solution: