Running Median Tracker Over an Operation Log
Data Structure DesignAuto-graded · 14 test casesLast updated
Process a log of insert and query operations on an integer stream, returning the current median for each query, using two heaps for efficient updates.
You are building a tracker that receives integers one at a time and can report the median of everything received so far. Instead of working with a class directly, your function replays a recorded log of operations and returns what each operation produced.
Median definition
Take all integers received so far and sort them.
- If the count is odd, the median is the middle value.
- If the count is even, the median is the average of the two middle values.
Operations
The log is given as two parallel lists, operations and arguments. The element at position i of arguments is the argument list for the operation at position i of operations.
| Operation | Argument list | Effect | Output entry |
|---|---|---|---|
"MedianFinder" | [] | Creates the empty tracker. It always appears first. | None |
"add_num" | [x] | Adds the integer x to the stream. | None |
"find_median" | [] | Computes the median of all integers added so far. | the median as a float |
Task
Implement median_tracker_log(operations, arguments). It should return a list with the same length as operations, where entry i is the output of operation i according to the table above.
Medians must be returned as floats (for example 2.0, not 2). When the count is even, compute the average without losing precision for very large or very small values; in Python this is naturally safe, but your logic should not rely on any fixed-width integer wraparound.
The structure should be efficient: inserting a number should take about O(log n) time and answering a median query about O(1) time.
Constraints
- Each added value
xsatisfies-2^31 <= x <= 2^31 - 1. - The log contains at most
100,000operations in total. find_medianis only issued after at least one number has been added."MedianFinder"appears once, as the first operation.len(operations) == len(arguments).- Duplicates and negative values may appear.
Examples
Example 1
Input: median_tracker_log(['MedianFinder', 'add_num', 'add_num', 'find_median', 'add_num', 'find_median'], [[], [1], [2], [], [3], []])
Output: [None, None, None, 1.5, None, 2]
Example 2
Input: median_tracker_log(['MedianFinder', 'add_num', 'add_num', 'find_median'], [[], [2147483647], [2147483647], []])
Output: [None, None, None, 2147483647]
Hints
Hint 1
Sorting everything on each query is too slow. Only the values around the middle of the sorted order matter for the median.
Hint 2
Keep the smaller half of the numbers in a max-heap and the larger half in a min-heap, with every value in the first half no larger than every value in the second.
Hint 3
Keep the sizes equal, or let the lower half hold exactly one extra element. After each insertion, move at most one element between heaps to restore this. In Python, simulate a max-heap by storing negated values.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Re-sorting the data for every query would cost O(n log n) each time. The median only depends on the boundary between the lower half and the upper half of the sorted data, so we maintain just that boundary with two heaps:
small: a max-heap holding the lower half (Python'sheapqis a min-heap, so we store negated values).large: a min-heap holding the upper half.
We maintain two invariants:
- Every element in
smallis less than or equal to every element inlarge. len(small)equalslen(large), or exceeds it by exactly one.
Insert x:
- If
smallis empty orx <= max(small), pushxintosmall; otherwise push it intolarge. This preserves invariant 1. - Rebalance. If
smallhas two more elements thanlarge, move the top ofsmallintolarge. Iflargehas more elements thansmall, move the top oflargeintosmall.
Query:
- If
smallhas more elements, the count is odd and the median ismax(small). - Otherwise the count is even and the median is
(max(small) + min(large)) / 2.0.
Why it is correct
With 2k+1 elements, small holds k+1 of them, all no larger than the k in large, so max(small) is the (k+1)-th smallest, which is the median. With 2k elements, each heap holds k, so max(small) and min(large) are the k-th and (k+1)-th smallest, the two middle values.
One insertion changes the size difference by at most one, so a single transfer restores balance. Moving the top of one heap to the other never breaks ordering, since that top is the extreme element adjacent to the boundary. Duplicates are fine because the <= comparison lets equal values land in either heap.
Python integers have arbitrary precision, so the sum of two middle values (at most 2^32 in magnitude) cannot overflow, and it is exactly representable as a float before the division by 2.0. In languages with 32-bit integers you would widen to 64-bit first.
Complexity
add_num:O(log n)(one push, and at most one pop and push to rebalance).find_median:O(1).- Space:
O(n).
Reference solution
import heapq
from typing import List, Optional
def median_tracker_log(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
small = [] # max-heap of the lower half, stored as negated values
large = [] # min-heap of the upper half
results = []
for operation, args in zip(operations, arguments):
if operation == "MedianFinder":
results.append(None)
elif operation == "add_num":
x = args[0]
if not small or x <= -small[0]:
heapq.heappush(small, -x)
else:
heapq.heappush(large, x)
if len(small) > len(large) + 1:
heapq.heappush(large, -heapq.heappop(small))
elif len(large) > len(small):
heapq.heappush(small, -heapq.heappop(large))
results.append(None)
else: # find_median
if len(small) > len(large):
results.append(float(-small[0]))
else:
results.append((-small[0] + large[0]) / 2.0)
return results