Replay Commands to Track a Running Median
Heaps, Sorting & SearchAuto-graded · 14 test casesLast updated
Replay a list of insert and query commands on a growing multiset of integers, reporting the median at each query; tests two-heap or order-statistic maintenance.
You are given a log of commands that act on a growing collection of integers. The collection starts empty. Process the commands in order and report what each one produces.
Two kinds of commands exist:
"addNum": its argument list holds exactly one integerx. Putxinto the collection. Duplicates are kept as separate items. This command producesNone."findMedian": its argument list is empty. Compute the median of everything added so far and produce it as a float.
Median. Sort the collection mentally.
- With an odd number of items, the median is the middle item.
- With an even number of items, the median is the average of the two middle items.
Input.
operations: a list of command names, each either"addNum"or"findMedian".arguments: a list of the same length asoperations. Entryiis the argument list for commandi([x]foraddNum,[]forfindMedian).
Output. A list with one entry per command, in order: None for each addNum, and the median as a float for each findMedian.
Rules.
- A
findMediancommand is only issued when the collection has at least one item. - If a command name is anything other than
"addNum"or"findMedian", raiseValueError.
A solution that handles each insertion in roughly O(log n) time and each query in O(1) or O(log n) time is expected.
Constraints
- The number of commands is up to about 10^5.
- Added values are integers; they may be negative and may repeat.
- Every
findMedianfollows at least oneaddNum.
Examples
Example 1
Input: running_median_log(['addNum', 'addNum', 'findMedian', 'addNum', 'findMedian'], [[1], [2], [], [3], []])
Output: [None, None, 1.5, None, 2]
Example 2
Input: running_median_log(['addNum', 'addNum', 'addNum', 'findMedian', 'addNum', 'findMedian'], [[-1], [-2], [-3], [], [4], []])
Output: [None, None, None, -2, None, -1.5]
Hints
Hint 1
Re-sorting the whole collection on every query is too slow. Think about which elements you actually need to see: only the one or two in the middle.
Hint 2
Keep the smaller half of the numbers in a max-heap and the larger half in a min-heap, so the middle elements sit at the two heap tops.
Hint 3
After each insertion, route the value to the correct half, then move at most one element between heaps so the lower half has the same size as the upper half or one more. Python's heapq is a min-heap, so store negated values for the lower half.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach. Split the numbers seen so far into two halves using two heaps:
small: a max-heap (implemented with negated values in Python) holding the lower half.large: a min-heap holding the upper half.
Two invariants are maintained after every insertion:
- Every element of
smallis less than or equal to every element oflarge. len(small)equalslen(large)orlen(large) + 1.
Then the median is read directly from the tops: for an odd count it is the top of small; for an even count it is the average of both tops.
Insertion. If small is empty or x is at most the maximum of small, push x into small; otherwise push it into large. This keeps the ordering invariant. The sizes may now be off by one, so if small has two more items than large, move its maximum to large; if large has more items than small, move its minimum to small. One move is always enough, because a single push shifts the size difference by exactly one.
Why it is correct. Routing keeps ordering because a value is placed in small only when it is no larger than the current maximum of small, which is already no larger than everything in large, and placed in large only when it is bigger than that maximum. Moving the maximum of small (or the minimum of large) across the boundary also keeps ordering. With n items, small holds the ceil(n/2) smallest, so its top is the middle element for odd n, and for even n the two tops are exactly the two middle elements. Duplicates are harmless because equal values are interchangeable.
Output details. The odd case returns float(...) and the even case divides by 2.0, so results are always floats. Unknown command names raise ValueError.
Complexity. Each addNum costs O(log n); each findMedian costs O(1). Space is O(n) for the heaps plus the output list.
import heapq
from typing import List, Optional
def running_median_log(operations: List[str], arguments: List[List[int]]) -> List[Optional[float]]:
small = [] # max-heap (negated values): lower half
large = [] # min-heap: upper half
out = []
for op, args in zip(operations, arguments):
if op == "addNum":
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))
out.append(None)
elif op == "findMedian":
if len(small) > len(large):
out.append(float(-small[0]))
else:
out.append((-small[0] + large[0]) / 2.0)
else:
raise ValueError("Unsupported operation")
return out