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 season total is posted once final. Wrong answers cost a point, so a total can be negative.

The league website shows the cutoff, which is the total a team currently needs to be in the top k. The cutoff must update as soon as each new total arrives.

Your task

Write a class FinalCutoff:

  • constructor(k, totals) receives k, the number of final places, and totals, the list of totals already posted, which may be empty.
  • add(total) records one more posted total and then returns the k-th highest total posted so far. If fewer than k totals have been posted, it returns 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

The top 3 starts as 42, 30 and 17. Adding 25 pushes out 17, so the cutoff is 25. Adding 50 pushes out 25, so the cutoff is 30. Adding 10 is too low to enter the top 3, so the cutoff stays 30. Adding 42 pushes out 30, so the top 3 is 50, 42 and 42, and the cutoff is 42.

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

With one total there is no 2nd place yet, so the result is null. After 8 is added, the top 2 is 8 and -5, so the cutoff is -5. Then 3 pushes -5 out, so the cutoff becomes 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

The brute force keeps every total in a list. On each add it appends the total, sorts the list from high to low, and reads position k - 1.

Each call costs O(n log n) for n totals so far. With 10,000 starting totals and 10,000 calls, each sort handles between 10,000 and 20,000 totals, which is about 2 billion steps for the season. Inserting into a sorted list is better, but shifting the 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