Solution: High Five
Let’s solve the High Five problem using the Hash Maps pattern.
We'll cover the following
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
.
Constraints:
items.length
items[i].length
For each
, 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 pairof a student, and for each pair: We append the
corresponding to the ID in dict
.We update
max_id
to themax_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 listresult
to store the final output.Next, we iterate through all possible IDs from 1 to
max_id
(inclusive) and check whether there are scores indict
for each ID. If there are, we do the following:We find the top
scores for the current student. We calculate the average of the top
scores using integer division. We append the pair
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:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.