Quant Memo
Coding/●●●●

A median structure that can also remove its median

Design a structure over a stream of numbers that supports:

  • add(x), insert a value.
  • peek_median(), return the current median (average of the two middles when the count is even).
  • pop_median(), remove and return the lower-middle element (for an odd count this is the unique median).
add(5); add(3); add(8)   # holds {3, 5, 8}, median 5
pop_median() -> 5        # now holds {3, 8}
peek_median() -> 5.5

Support add and pop_median in O(logn)O(\log n) and peek_median in O(1)O(1).

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions