High Five

For each student, return the average of their top 5 scores — group then partial sort.

Easy
Time O(N log N) Space O(N)
LeetCode
5 min read
hash-map sorting heap

Problem#

Given a list of [studentId, score] pairs, return for each student [studentId, average] where average is the integer average (floor division) of their top 5 scores. Sort the result by studentId ascending.

Examples#

  • [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]][[1,87],[2,88]].

Constraints#

  • 1 <= items.length <= 1000, each student has at least 5 scores.

Hints#

Hint
Per student, keep a min-heap of size 5; cap at 5 as you scan.

Approach#

Group scores by student in a map<int, priority_queue<int, vector<int>, greater<>>> (sorted student id, min-heap of size 5). For each score: push, then pop while size exceeds 5. After ingestion, each heap holds the top 5; sum and divide by 5.

Solution#

High Five
class Solution {
public:
vector<vector<int>> highFive(vector<vector<int>>& items) {
map<int, priority_queue<int, vector<int>, greater<int>>> top5;
for (auto& it : items) {
auto& pq = top5[it[0]];
pq.push(it[1]);
if ((int)pq.size() > 5) pq.pop();
}
vector<vector<int>> ans;
for (auto& [id, pq] : top5) {
int sum = 0;
while (!pq.empty()) { sum += pq.top(); pq.pop(); }
ans.push_back({id, sum / 5});
}
return ans;
}
};

Editorial#

std::map (red-black tree) keeps keys sorted so the final pass is already in studentId order — no extra sort step. The bounded min-heap drops the smallest score when size exceeds 5, leaving exactly the top 5. Note: integer division (floor) matches the problem’s “average” definition.

Complexity#

  • Time: O(N log N) — map ops are O(log K) and heap ops are O(log 5).
  • Space: O(N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.