Skip to the code
cf.
+25 XP

#395 Median Tracker for a Live Chart

medium

A live chart shows a horizontal line at the median of all values received so far. Values arrive one at a time, and the chart asks for the median whenever it redraws.

Write a class MedianTracker with:

  • constructor(): starts empty.
  • add(value): records a number. Returns nothing.
  • median(): returns the median of all recorded numbers (the average of the two middle ones for an even count). It is only called after at least one add.

Each example lists the calls in order, then each call's arguments. The first call creates the object with new MedianTracker(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["MedianTracker","add","add","median","add","median"]
[[],[10],[20],[],[15],[]]
Output: [null,null,null,15,null,15]

[10, 20] has median 15; [10, 15, 20] also has median 15.

Example 2

Input: ["MedianTracker","add","median","add","median"]
[[],[-3],[],[4],[]]
Output: [null,null,-3,null,0.5]

The average of -3 and 4 is 0.5.

Constraints

  • -10^5 <= value <= 10^5
  • At most 5 * 10^4 calls.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).