Running medians
Return the median after every prefix of an integer stream. For even prefixes average the two middle values. Use O(log n) work per insertion.
import heapq
lower = [-2, -1]
upper = [5, 7]
print((-lower[0]+upper[0])/2)Reason about the state
Maintain a max-heap for the lower half and a min-heap for the upper half. Rebalance so the lower half has equal size or one extra item. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return the median after every prefix of an integer stream. For even prefixes average the two middle values. Use O(log n) work per insertion.
The explanation opens here once every check passes.