Running Median with Power-of-Two Bucket Tracking
Heaps, Sorting & SearchAuto-graded · 24 test casesLast updated
Tests two-heap streaming median maintenance combined with exact integer floor-log₂ bucketing to place each median into its enclosing power-of-two interval.
Running Median with Power-of-Two Bucket Tracking
You are given a sequence of positive integers arriving one at a time. After each new value is consumed, compute two things:
-
Running median — the median of all values seen so far. When the count of values is odd, the median is the single middle value. When the count is even, the median is the arithmetic mean of the two middle values (which may be a half-integer such as
3.5). -
Power-of-two interval — the unique pair
[L, R]whereL = 2^kandR = 2^(k+1)for the integerksatisfying2^k ≤ median < 2^(k+1). In other words,Lis the largest power of two that does not exceed the median, andRis the next power of two above it.
Return a list of results, one per value in the input. Each result is a two-element list [median, [L, R]].
Details
- The input list contains only positive integers, so the median is always at least 1 and the interval always exists.
- For a median that is itself an exact power of two (e.g.,
4), the interval is[4, 8]— the half-open convention[2^k, 2^(k+1))applies, placing the left endpoint in the bucket. - For a half-integer median such as
1.5, floor it to findk:floor(1.5) = 1, so the interval is[1, 2]. - Return
medianas a Pythonintwhen the count is odd, and as a Pythonfloat(e.g.,1.5) when the count is even and the two middle values have an odd sum; return anintwhen the count is even and their sum is even.
Constraints
1 ≤ len(values) ≤ 10^51 ≤ values[i] ≤ 10^9- All elements are positive integers.
- The returned list has exactly
len(values)entries. - Each entry is
[median, [L, R]]whereLandRare positive integers andR = 2 * L.
Examples
Example 1
Input: running_median_with_power_interval([5, 15, 1, 3])
Output: [[5, [4, 8]], [10, [8, 16]], [5, [4, 8]], [4, [4, 8]]]
Example 2
Input: running_median_with_power_interval([1, 2])
Output: [[1, [1, 2]], [1.5, [1, 2]]]
Example 3
Input: running_median_with_power_interval([1, 3])
Output: [[1, [1, 2]], [2, [2, 4]]]
Example 4
Input: running_median_with_power_interval([2, 4, 8, 16])
Output: [[2, [2, 4]], [3, [2, 4]], [4, [4, 8]], [6, [4, 8]]]
Hints
Hint 1
Keep two heaps: a max-heap holding the smaller half of values seen so far, and a min-heap holding the larger half. After each insertion, rebalance so the max-heap is either the same size as the min-heap or exactly one element larger — that way the median is always at or near the top of the max-heap.
Hint 2
To avoid floating-point imprecision when the count is even, work with twice the median: add the two heap tops as integers. You only produce a float in the final step if that sum is odd.
Hint 3
To find k such that 2^k ≤ median < 2^(k+1), compute floor(median) and use its bit length. For a fraction p/q, find k by checking (1 << k) * q ≤ p and (1 << (k+1)) * q > p using only integer arithmetic — no math.log needed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two-heap streaming median
The core idea is to split the values seen so far into two halves using two heaps:
lower: a max-heap holding the smaller half (implemented by negating values in Python's min-heap).upper: a min-heap holding the larger half.
Two invariants are maintained after every insertion:
- Every element in
loweris ≤ every element inupper. len(lower)equalslen(upper)orlen(lower) == len(upper) + 1.
With these invariants, the median is always accessible in O(1):
- Odd total count → the median is
top(lower)(the single middle element). - Even total count → the median is
(top(lower) + top(upper)) / 2.
Insertion routes x to lower when x ≤ top(lower), otherwise to upper, preserving invariant 1. Then at most one element is moved between heap tops to restore invariant 2. The whole operation costs O(log n).
Avoiding floating-point imprecision
Rather than dividing immediately, we track the median as a fraction numerator / denominator:
- Odd count:
numerator = top(lower),denominator = 1. - Even count:
numerator = top(lower) + top(upper),denominator = 2.
This keeps all intermediate values as exact integers.
Power-of-two interval via integer bit operations
We need k such that 2^k ≤ median < 2^(k+1), equivalently k = floor(log₂(median)).
For a fraction p/q this means 2^k * q ≤ p < 2^(k+1) * q. A good starting estimate is k = p.bit_length() - q.bit_length(), then one or two integer comparisons nudge it into the correct position. No floating-point math.log is involved, so there is no precision loss for any input size.
Boundary case — median is an exact power of two: The half-open convention [2^k, 2^(k+1)) places it in the lower bucket, which is what the bit-length arithmetic naturally produces.
Boundary case — half-integer median: Flooring a value like 3.5 to 3 before bucketing is correct because floor(log₂(m)) = floor(log₂(floor(m))) for all real m ≥ 1.
Why the invariants are preserved
After routing x and rebalancing, lower holds the ⌈n/2⌉ smallest values. So top(lower) is exactly the lower-middle element, and top(upper) is the upper-middle element. Moving the extreme top of the larger heap to the smaller heap keeps invariant 1 because that top is the element closest to the cut.
Complexity
- Time: O(n log n) overall — each of the n insertions costs O(log n) for heap operations; the median and interval are O(1) per step.
- Space: O(n) — every value is stored in one of the two heaps.
import heapq
from typing import List
def running_median_with_power_interval(values: List[int]) -> List[List]:
lower = [] # max-heap (negate values to use Python's min-heap)
upper = [] # min-heap
result = []
def power_interval(numerator: int, denominator: int) -> List[int]:
# Find k such that 2^k <= numerator/denominator < 2^(k+1)
# using pure integer arithmetic to stay exact.
k = numerator.bit_length() - denominator.bit_length()
# Adjust down if the initial estimate overshoots
while (1 << k) * denominator > numerator:
k -= 1
# Adjust up if the estimate is too low
while (1 << (k + 1)) * denominator <= numerator:
k += 1
return [1 << k, 1 << (k + 1)]
for x in values:
# Route x into the correct heap
if not lower or x <= -lower[0]:
heapq.heappush(lower, -x)
else:
heapq.heappush(upper, x)
# Rebalance: lower may be equal in size or one larger than upper
if len(lower) > len(upper) + 1:
heapq.heappush(upper, -heapq.heappop(lower))
elif len(upper) > len(lower):
heapq.heappush(lower, -heapq.heappop(upper))
# Compute median and represent it as numerator/denominator
if len(lower) == len(upper):
a = -lower[0]
b = upper[0]
total = a + b
if total % 2 == 0:
median = total // 2
numerator, denominator = median, 1
else:
median = total / 2.0
numerator, denominator = total, 2
else:
median = -lower[0]
numerator, denominator = median, 1
result.append([median, power_interval(numerator, denominator)])
return result