CJCoding With Joseph
15free / daySign inCreate account

Track the Running Median With Two Heaps

Complete add(int value) and median() so MedianTracker can report the median of every number added so far, at any moment, without sorting the numbers again each time.

Reminder: two heaps, two halves. A heap gives fast access to only ONE end of its values: a max heap to its largest, a min heap to its smallest. Java's PriorityQueue<Integer> is a min heap by default, and new PriorityQueue<Integer>(Collections.reverseOrder()) turns it into a max heap. Neither one can find the middle on its own, but two of them together can.

Split the numbers into two halves. low is a max heap holding the smaller half, so its top is the biggest of the small numbers. high is a min heap holding the larger half, so its top is the smallest of the big numbers. The median always sits on one or both of those two tops.

numbers so far:  1 3 5 15
low  (max heap): 3 1     top = 3
high (min heap): 5 15    top = 5     median = (3 + 5) / 2.0 = 4.0

Requirements: 1. add(int value) puts value into low when low is empty or value is less than or equal to the top of low, otherwise into high. 2. Then rebalance: low may hold at most ONE more number than high, and high may never hold more than low. When either rule breaks, move the top of the bigger heap into the other heap. 3. median() returns 0.0 when nothing has been added, the top of low when low holds more numbers, and the average of both tops as a double (divide by 2.0) when the halves are the same size. 4. Do not change the two heap fields or count().

Do NOT write a main method.

Expected Output:

5.0
10.0
5.0
4.0
4

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Data Structures & AlgorithmsHeaps
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (sysout, psvm, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.