InferenceAI

Enter at least two characters to search.

Start free

Running Median

hardHeaps40 min50 XP

Numbers arrive one at a time. After each arrival, record the median of all numbers so far (the average of the two middle values when the count is even). Return the list of medians as floats.

Requirements

  • O(log⁡n)O(\log n) per number with two heaps: a max-heap for the lower half and a min-heap for the upper half.

Examples

EXAMPLE WALKTHROUGHclassic

A guided view of the published example, not a trace of your code.

INPUT[[5,15,1,3]]
TASKrunning_median()
EXPECTED OUTPUT[5,10,5,4]

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [5,15,1,3]

Output: [5,10,5,4]

Explanation: classic

Input: nums = [1]

Output: [1]

Explanation: single

Input: nums = [2,2,2]

Output: [2,2,2]

Explanation: equal

Hint 1

Keep the halves balanced so the lower half has the same size or one more element.

Hint 2

The median comes from the heap tops.

Topics

DSAHeapsPython