Skills101
← All coding problems

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 number x
  • median — 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 q lines: one operation each. The first operation is always an add.

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).

Loading editor…

Log in to run and submit your code — it's free.