Live Median House Price

HardheapAlso known as Find Median from Data Stream

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

Sales are reported one at a time as they close, and the page shows the updated median right away. By the end of the year there are thousands of sales, and recomputing from scratch every time makes the page slow.

Your task

Write a class MedianPrice:

  • constructor(): no sales yet.
  • addSale(price): record one sale.
  • median(): return the median of all prices recorded so far. With an odd number of sales it is the middle price once they are sorted; with an even number it is 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. Two sales, 250000 and 300000: the average of the two is 275000. Add the 2,000,000 mansion: the sorted prices are 250000, 300000, 2000000, so the median is 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, so the answer is 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 every time median() is called. That costs O(n log n) per call, so a year of 25,000 sales with a median after each is about 4 billion steps.

Keeping the list sorted by inserting each price in its place (binary search for the spot) is better, but inserting into the middle of an array still shifts up to n elements, so it is O(n) per sale and 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