The problem
Values arrive one at a time. After any of them, you may be asked for the median of all values so far: the middle value once they are sorted, or the average of the two middle values when the count is even. Return it as a float.
m = MedianFinder()
m.add(5); m.median() # 5.0
m.add(15); m.median() # 10.0
m.add(1); m.median() # 5.0
m.add(3); m.median() # 4.0
median is only called after at least one add. Values are integers and can repeat.
The modules heapq and bisect are switched off.
One test passes in numbers that count how often they are compared with <, <=, > or >=. They behave like ordinary numbers otherwise. This is how the tests tell an O(log n) heap step from an O(n) scan, which a timer cannot always do.
Limits
- Up to 50,000 values, with a median after each.
addshould take O(log n) comparisons andmedianO(1).
Builds on HEAP-6 Median of a stream.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Odd and even | Not run | |
| 2 | Lesson 6's stream | Not run | |
| 3 | Repeated values | Not run | |
| 4 | Negative values | Not run | |
| 5 | Increasing | Not run | |
| 6 | Decreasing | Not run | |
| 7 | Comparisons | Not run | |
| 8 | 50,000 values | Not run |