Live Median House Price

HardheapAlso known as Find Median from Data Stream

A local news site's housing page shows one headline number: this year's median sale price in town. The median, not the average, because one mansion selling for millions would drag the average far above a typical home.

Sales arrive one at a time as they close, and the page updates the median right away. With thousands of sales, recomputing from scratch each time is too slow.

Your task

Write a class MedianPrice:

  • constructor() creates a tracker with no sales.
  • addSale(price) records one sale.
  • median() returns the median of all prices so far. With an odd number of sales, the middle price once sorted; with an even number, the average of the two middle prices (which may end in .5). With no sales, return null (None in Python).

addSale should take O(log n) time and median O(1), where n is the number of sales so far.

class MedianPrice

Examples

Example 1
Input
new MedianPrice()
.addSale(300000)
.median()
.addSale(250000)
.median()
.addSale(2000000)
.median()
.addSale(280000)
.median()
Output
[null, null, 300000, null, 275000, null, 300000, null, 290000]
Why

One sale: 300000. Add 250000: the average of the two is 275000. Add the 2,000,000 mansion: sorted 250000, 300000, 2000000, median 300000; the mansion barely moves it. Add 280000: the middle two are 280000 and 300000, median 290000.

Example 2
Input
new MedianPrice()
.median()
.addSale(5)
.addSale(6)
.median()
Output
[null, null, null, null, 5.5]
Why

Before any sale there is no median: null. After 5 and 6 the median is 5.5, not always a whole number.

Constraints

  • 1 ≤ price ≤ 10,000,000 (whole dollars). Prices may repeat.
  • At most 50,000 calls in total.
  • Every median is a whole number or ends in .5, so answers are compared exactly.
Start with brute force

Keep all prices in a list and sort it on every median() call: O(n log n) per call, about 4 billion steps for 25,000 sales with a median after each.

Keeping the list sorted (binary search for the spot) is better, but inserting into the middle of an array shifts up to n elements: O(n) per sale, O(n²) for the year.

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