Group the scores by student in a Map, sort each student's scores from high to low, average the first five, and sort the result by student id. Two details decide whether it is right: the comparator ((a, b) => b - a, because the default sort compares as strings and puts 100 before 9), and the rounding (the classic version wants the integer part, Math.floor). Then improve it: only a student's best five can matter, so keep a small sorted list of at most five per student while reading, instead of storing and sorting everything. Say what happens when a student has fewer than five scores; here, the average of the ones they have.
LeetCode-style: "high five problem" variant (sort + average scores per student).
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
The Map keeps one array of scores per student. Each array is sorted high to low with a numeric comparator, cut to five, summed with reduce and divided by how many there are. The final sort orders the rows by id. Sorting each student's scores costs O(s log s) for s scores, and every score is kept in memory.
// items is a list of [studentId, score]. For each student, average their five highest scores// (rounded down, as the well-known version of this problem asks) and return [id, average]// pairs sorted by id.function highFive(items) {const byStudent = new Map();for (const [id, score] of items) {if (!byStudent.has(id)) byStudent.set(id, []);byStudent.get(id).push(score);}return [...byStudent].map(([id, scores]) => {const top = scores.sort((a, b) => b - a).slice(0, 5);const sum = top.reduce((total, s) => total + s, 0);return [id, Math.floor(sum / top.length)];}).sort((a, b) => a[0] - b[0]);}
passes 7 checks run on every build, against the native method where there is one
- the classic example
- only the five highest count
- the average is rounded down
- sorted by id, whatever order the scores arrive in
- fewer than five scores: the average of what there is
- repeated scores are separate scores
- no items, and the input is left alone
Each student's list holds at most n scores, highest first. A new score that would not make the list is skipped at once; otherwise it is inserted at its place and the lowest is dropped. With n fixed at five that is constant work per score, so the whole thing is one pass, and memory is five numbers per student however many scores arrive. For a large n, a min-heap does the same job in O(log n) per score.
// No need to keep or sort every score: only a student's best n can matter. Each new score is// inserted in order into a list that never grows past n, so memory is n per student and a score// costs at most n steps, however many there are.function highFive(items, n = 5) {const best = new Map(); // id → up to n scores, highest firstfor (const [id, score] of items) {let top = best.get(id);if (!top) best.set(id, (top = []));if (top.length === n && score <= top[n - 1]) continue; // would not make the top nlet at = top.length;while (at > 0 && top[at - 1] < score) at--;top.splice(at, 0, score);if (top.length > n) top.pop();}return [...best].map(([id, top]) => [id, Math.floor(top.reduce((total, s) => total + s, 0) / top.length)]).sort((a, b) => a[0] - b[0]);}
passes 9 checks run on every build, against the native method where there is one
- the classic example
- only the five highest count
- the average is rounded down
- sorted by id, whatever order the scores arrive in
- fewer than five scores: the average of what there is
- repeated scores are separate scores
- no items, and the input is left alone
- the best n, for any n
- agrees with sorting everything, on many scores
Interviewers change the output more often than the idea. Here records are objects, the average keeps two decimals, rows are ordered by average and then by name, and equal averages share a rank with the next rank skipped (1, 1, 3). Invalid scores throw instead of becoming NaN in an average. The comparator returns the difference of the averages, and only when that is zero falls through to the name comparison.
// The variant: records are objects, the result is a ranking. Average of each student's best// `top` scores to two decimals, highest average first, ties in name order sharing a rank// (1, 1, 3). A score that is not a number is an error, not a zero.function leaderboard(records, top = 5) {const best = new Map();for (const { student, score } of records) {// Number.isFinite does not convert: '90', null and NaN are all rejected.if (!Number.isFinite(score)) {throw new TypeError(`score for ${student} is not a number`);}let scores = best.get(student);if (!scores) best.set(student, (scores = []));if (scores.length === top && score <= scores[top - 1]) continue;let at = scores.length;while (at > 0 && scores[at - 1] < score) at--;scores.splice(at, 0, score);if (scores.length > top) scores.pop();}const rows = [...best].map(([student, scores]) => {const mean = scores.reduce((total, s) => total + s, 0) / scores.length;return { student, scores, average: Math.round(mean * 100) / 100 };});rows.sort((a, b) => b.average - a.average || (a.student < b.student ? -1 : a.student > b.student ? 1 : 0));rows.forEach((row, i) => {row.rank = i > 0 && rows[i - 1].average === row.average ? rows[i - 1].rank : i + 1;});return rows;}
passes 8 checks run on every build, against the native method where there is one
- highest average first, ties share a rank and the next rank is skipped
- each row carries the scores that were counted, highest first
- a smaller top changes the ranking
- only the best five count
- averages keep two decimals
- three tied, then one: ranks 1, 1, 1, 4
- a score that is not a number throws
- no records
The default sort is alphabetical
[100, 9, 80].sort() gives [100, 80, 9]: without a comparator, elements are converted to strings and compared by UTF-16 code units. Sorting numbers always needs (a, b) => a - b or b - a.
Grouping is built in now
Map.groupBy(items, ([id]) => id) and Object.groupBy do the grouping step in one call in current browsers and Node.
Leaderboards and dashboards
"Top N per group" is one of the most common shapes of report: best scores per player, slowest requests per route, largest orders per customer. On big data it is done exactly as in the second stage, with a bounded list or heap per group.
Calling
sort()with no comparator on numbers.Dividing by 5 when a student has fewer than five scores.
Forgetting the final sort by id and relying on the order students happened to appear in.
Using a plain object for the groups and getting string ids back (
'1'instead of1).Rounding with
Math.roundwhen the problem asks for integer division.Sorting all scores of all students together when only five per student matter.
What is the complexity?
With N scores: grouping is O(N). Sorting each student's scores is O(N log N) in the worst case (one student has them all). The bounded-list version is O(N · n) with n = 5, which is O(N), and O(students · n) memory. The final sort by id is O(S log S) for S students.
When would you use a heap?
When n is large. A min-heap of size n gives O(log n) per score instead of O(n) for the insertion into a sorted list. For five, the sorted list is simpler and faster in practice.
Does sort change the input?
sort sorts in place. In the first stage it sorts the arrays the function built itself, so the caller's items is untouched. If you were handed the score arrays, use toSorted or copy first.
How would ties be ranked differently?
Dense ranking gives 1, 1, 2 instead of 1, 1, 3: increase the rank by one each time the average changes, instead of using the row's position.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/groupBy
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted