Find Median from Data Stream
hardHeap / Priority Queue+40 XPTime limit 2s
Numbers arrive one at a time. Support two operations:
add x— add the numberxmedian— print the median of all numbers added so far (for an even count, the average of the two middle numbers)
Input:
- line 1:
q - next
qlines: one operation each. The first operation is always anadd.
Output: one line per median, with exactly one digit after the decimal point (2.0, -1.5).
Constraints: 1 ≤ q ≤ 10⁵, −10⁵ ≤ x ≤ 10⁵.
The design: keep the smaller half in a max-heap and the larger half in a min-heap, with sizes differing by at most one. The median is then the top of one heap or the average of both tops: O(log n) per add, O(1) per median. Sorting after every add is far too slow for the big tests.
Sample input 1
5 add 1 add 2 median add 3 median
Sample output 1
1.5 2.0
Sample input 2
2 add -5 median
Sample output 2
-5.0
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).