High Five

easy hash map sorting heap

Problem

You are given a list of scores of different students, items, where items[i] = [IDi, scorei] represents one score from a student with IDi, where IDi can appear multiple times. For each student, compute their top-five average: the sum of their five highest scores divided by 5 using integer division. Return the result as an array of [ID, topFiveAverage] pairs sorted by ID in ascending order.

Inputitems = [[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]]
Student 1's top five are 100, 92, 91, 87, 65 → sum 435, average 435 // 5 = 87. Student 2's top five are 100, 97, 93, 77, 76 → sum 443, average 443 // 5 = 88.

def high_five(items):
    scores = {}
    for sid, score in items:
        scores.setdefault(sid, []).append(score)
    result = []
    for sid in sorted(scores):
        top = sorted(scores[sid], reverse=True)[:5]
        result.append([sid, sum(top) // 5])
    return result
function highFive(items) {
  const scores = new Map();
  for (const [sid, score] of items) {
    if (!scores.has(sid)) scores.set(sid, []);
    scores.get(sid).push(score);
  }
  const ids = [...scores.keys()].sort((a, b) => a - b);
  return ids.map(sid => {
    const top = scores.get(sid).sort((a, b) => b - a).slice(0, 5);
    const sum = top.reduce((a, b) => a + b, 0);
    return [sid, Math.floor(sum / 5)];
  });
}
class Solution {
    public int[][] highFive(int[][] items) {
        Map<Integer, List<Integer>> scores = new TreeMap<>();
        for (int[] it : items)
            scores.computeIfAbsent(it[0], k -> new ArrayList<>()).add(it[1]);
        List<int[]> res = new ArrayList<>();
        for (Map.Entry<Integer, List<Integer>> e : scores.entrySet()) {
            List<Integer> s = e.getValue();
            s.sort(Collections.reverseOrder());
            int sum = 0;
            for (int i = 0; i < 5; i++) sum += s.get(i);
            res.add(new int[]{ e.getKey(), sum / 5 });
        }
        return res.toArray(new int[0][]);
    }
}
vector<vector<int>> highFive(vector<vector<int>>& items) {
    map<int, vector<int>> scores;
    for (auto& it : items) scores[it[0]].push_back(it[1]);
    vector<vector<int>> res;
    for (auto& [sid, s] : scores) {
        sort(s.rbegin(), s.rend());
        int sum = 0;
        for (int i = 0; i < 5; i++) sum += s[i];
        res.push_back({ sid, sum / 5 });
    }
    return res;
}
Time: O(n log n) Space: O(n)