Running Median Over a Command Log of Inserts and Queries
Heaps, Sorting & SearchAuto-graded · 16 test casesLast updated
Process a log of insert and query commands on a growing multiset of integers, reporting the median at each query using two heaps for efficient updates.
You are given a log of commands that act on a growing collection of integers, which starts out empty. The commands are supplied as two parallel lists of equal length:
commands[i]is the name of the i-th command.payloads[i]is a list of arguments for that command.
Two command names exist:
"addNum":payloads[i]holds exactly one integer. Insert it into the collection (duplicates are allowed and each copy counts separately). This command produces no result."findMedian":payloads[i]is an empty list. Report the median of every integer inserted so far.
Median definition. Sort all inserted integers. If their count is odd, the median is the middle value. If the count is even, the median is the average of the two middle values.
Output. Return a list with one entry per command, in the same order as the input:
Nonefor each"addNum"command.- The median as a floating-point number for each
"findMedian"command (for example2.0rather than2, and1.5for the average of 1 and 2).
Any unrecognized command name is not expected to appear in the input.
Aim for an approach where each insertion costs about O(log n) and each median query costs O(1), rather than re-sorting the collection for every query.
Constraints
- The total number of commands is at most 100,000.
- Each inserted integer lies in the range -10^6 to 10^6.
"findMedian"is only issued after at least one integer has been inserted.commandsandpayloadshave the same length.- Edge cases to handle: a single inserted element, all-identical elements, and negative values and zero.
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', 'findMedian', 'addNum', 'findMedian'], [[-1], [], [-2], []])
Output: [None, -1, None, -1.5]
Hints
Hint 1
Splitting the numbers into a smaller half and a larger half means the median always sits at the boundary between them, so you never need the full sorted order.
Hint 2
Use a max-heap for the smaller half and a min-heap for the larger half. Python's heapq is a min-heap, so store negated values for the max-heap.
Hint 3
After every insertion, keep the two halves ordered (everything in the smaller half is at most everything in the larger half) and keep their sizes equal, or with the smaller half holding exactly one extra element. One element transfer is always enough to rebalance.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the numbers inserted so far into two halves:
small: the lower half, stored in a max-heap (implemented by pushing negated values into Python's min-heap), so its largest element is available in O(1).large: the upper half, stored in a min-heap, so its smallest element is available in O(1).
Two invariants hold after every insertion:
- Ordering: every element of
smallis less than or equal to every element oflarge. - Balance:
len(small)equalslen(large), or exceeds it by exactly one.
Insertion. If small is empty or the new value is at most the top of small, push it into small; otherwise push it into large. Then rebalance: if small is too big by two, move its maximum to large; if large is bigger than small, move its minimum to small. A single insertion shifts the size difference by at most one, so one transfer is always enough. Each transfer moves an element across the boundary, so ordering is preserved.
Query. If small has more elements, the median is its top. Otherwise the counts are equal and the median is the average of the two tops. The result is always returned as a float.
Why it is correct
With n elements inserted, the invariants mean small holds the ⌈n/2⌉ smallest and large holds the ⌊n/2⌋ largest. For odd n, the maximum of small is the ⌈n/2⌉-th smallest value, which is the middle element. For even n, the two middle elements of the sorted order are exactly the maximum of small and the minimum of large. Duplicates are fine because the ordering invariant allows equality across the boundary.
Complexity
- Insertion: O(log n) (at most one push, plus one pop and push to rebalance).
- Median query: O(1).
- Space: O(n).
Reference solution
import heapq
from typing import List, Optional
def running_median_log(commands: List[str], payloads: List[List[int]]) -> List[Optional[float]]:
small = [] # max-heap of the lower half, stored as negated values
large = [] # min-heap of the upper half
out = []
for cmd, args in zip(commands, payloads):
if cmd == "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 cmd == "findMedian":
if len(small) > len(large):
out.append(float(-small[0]))
else:
out.append((-small[0] + large[0]) / 2.0)
else:
raise ValueError("Unknown command")
return out