Quiz League Final Cutoff

MediumheapAlso known as Kth Largest Element in a Stream

A pub quiz league sends its best k teams to a grand final. Teams finish their seasons on different nights, and each one's season total is posted as soon as it is final. Wrong answers cost a point, so a total can be negative.

The league website shows one number: the cutoff, meaning the total you currently need to be in the top k. It has to update the moment each new total arrives, all season long.

Your task

Write a class FinalCutoff:

  • constructor(k, totals): k is the number of final places; totals is the list of totals already posted (it may be empty).
  • add(total): record one more posted total, then return the k-th highest total posted so far. If fewer than k totals have been posted, return null (None in Python).

Equal totals take separate places: if the top totals are 50, 50 and 40, the 2nd highest is 50 and the 3rd is 40.

class FinalCutoff

Examples

Example 1
Input
new FinalCutoff(3, [42, 17, 30])
.add(25)
.add(50)
.add(10)
.add(42)
Output
[null, 25, 30, 30, 42]
Why

Top 3 starts as 42, 30, 17. Adding 25 knocks out 17: top 3 is 42, 30, 25, cutoff 25. Adding 50 knocks out 25: cutoff 30. Adding 10 is too low to matter: still 30. Adding 42 knocks out 30: top 3 is 50, 42, 42, cutoff 42.

Example 2
Input
new FinalCutoff(2, [])
.add(-5)
.add(8)
.add(3)
Output
[null, null, -5, 3]
Why

With one total posted there is no 2nd place yet, so the answer is null. After 8 arrives the top 2 is 8, -5, so the cutoff is -5. Then 3 pushes -5 out: cutoff 3.

Constraints

  • 1 ≤ k ≤ 10,000
  • 0 ≤ totals.length ≤ 10,000
  • -1,000 ≤ each total ≤ 1,000
  • At most 10,000 calls to add.
Start with brute force

Keep every total in a list. On each add, append, sort from high to low, and read position k - 1.

Each call costs O(n log n) where n is everything posted so far. With 10,000 starting totals and 10,000 calls, each sort handles 10,000 to 20,000 totals, so the season costs about 2 billion steps. Keeping the list sorted by inserting in place is better, but shifting elements still costs O(n) per call.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code