← Questions
Running median of a stream
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Dec 2025. It tests heaps and streaming.
Integers arrive one at a time. After each one, report the median of everything seen so far. To keep the output exact, report twice the median: for an odd count, two times the middle value; for an even count, the sum of the two middle values.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
running_median_twice(values: list[int]) -> list[int]— one number per input value, in order;[]for an empty input. - Or as a class:
add(x: int) -> Noneandmedian_twice() -> int.
Example
running_median_twice([5, 2, 8, 1]) -> [10, 7, 10, 7] # medians 5, 3.5, 5, 3.5
running_median_twice([-2, -2, 4]) -> [-4, -4, -4] # duplicates count with multiplicity
running_median_twice([7]) -> [14]
Constraints
-
0 <= len(values) <= 2 · 10^5. -
-10^9 <= values[i] <= 10^9; doubled values need 64 bits. - Target O(n log n) time and O(n) space.
Clarifying questions
- For an even count, is the median the mean of the two middle values?
- Can values repeat, and are they integers?
- Is memory bounded, or may I keep every value?
- Are queries interleaved with inserts, or only one per insert?
What a strong answer covers
- Two heaps: a max-heap for the lower half and a min-heap for the upper half. Invariant: every lower value is
<=every upper value, and the lower heap has the same size as the upper or one more. - Each insert pushes to one side, moves the top across if the ordering breaks, then rebalances sizes. O(log n) per insert, O(1) to read.
- Why re-sorting each prefix (O(n^2 log n)) is too slow.
- Overflow when doubling or adding the middle values.
- Tests: descending input, all equal, negative values, alternating parity.
Follow-ups
- All values come from a small range such as 0 to 100. Use a count per value and walk to the middle, O(range) per query or better with a pointer that moves.
- Report the k-th smallest for any
k, not just the middle. Which structures still work (an order-statistic tree, a Fenwick tree over compressed values)? - The stream is too large to keep. Give an approximate median with bounded memory (t-digest, quantile sketches).
- Report the median of only the last
wvalues (a sliding window, which needs deletion).
Where it's asked
- Google · Onsite coding · Last asked Dec 202545 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
