Numbers arrive one at a time. After each number, report the median of everything received so far.
What to build
A program that prints the median after each new number.
Requirements
- The median of an odd count is the middle number; for an even count it is the average of the two middle numbers.
- Print each median as a whole number or with
.5, for example2,3.5. - Use two heaps, so each number costs O(log n).
Input
The first line has n. The second line has the n positive integers.
Output
The n medians, separated by spaces.
Constraints
1 ≤ n ≤ 1000; numbers from 1 to 10⁴.
Example
Input:
5
2 1 5 7 2
Output:
2 1.5 2 3.5 2
Why it works
The two heaps hold the lower half and the upper half of the numbers, balanced in size. The median is then always at the tops, found in O(1), and adding a number needs only a push and at most one move between the heaps.
Examples
5 2 1 5 7 2
2 1.5 2 3.5 2
1 4
4
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep two heaps: a max-heap (store negatives) for the smaller half and a min-heap for the larger half.
Hint 2
Keep their sizes equal, or the small half one bigger. Then the median is the top of the small half, or the average of both tops.
Hint 3
The average of two whole numbers is either whole or ends in .5; print `x.5` without using floats.
Solution
Show one correct solution (try it yourself first)
import heapq
n = int(input())
nums = list(map(int, input().split()))
low = []
high = []
out = []
for x in nums:
heapq.heappush(low, -x)
heapq.heappush(high, -heapq.heappop(low))
if len(high) > len(low):
heapq.heappush(low, -heapq.heappop(high))
if len(low) > len(high):
out.append(str(-low[0]))
else:
s = -low[0] + high[0]
out.append(str(s // 2) if s % 2 == 0 else str(s // 2) + ".5")
print(*out)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step