Skip to the solution
HardDSA15 min read

How do you find the median from a data stream?

240 views

The problem

Question presented to candidate: "Numbers arrive one at a time. Design a Python class with add_num(x) and find_median(), where find_median returns the median of everything added so far. Both calls happen many times, so tell me the cost of each."

What a strong answer should cover:

  • Why sorting on every query (O(n log n)) and keeping a sorted list (O(n) per insert) are too slow for long streams.
  • Two heaps: a max-heap for the lower half and a min-heap for the upper half; O(log n) add, O(1) median.
  • The invariant: every number in the lower half โ‰ค every number in the upper half, and the sizes differ by at most one.
  • Python details: heapq is a min-heap only, so the lower half stores negated values; use / 2 (true division) for the even case, not // 2.
  • Follow-ups: values in a small range (counting buckets), removals (sliding window), percentiles other than 50%.

Clarifying questions expected:

  • For an even count, average the two middle values or return the lower one?
  • What range can the values take, and can they be removed?

Code / implementation expected: Yes โ€” a MedianFinder class built on two heapq lists, in Python 3.

  • heap
  • design

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read ยท 15 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonMedianFinder: the median after every add (3 streams)
PythonSort every time vs sorted insert vs two heaps vs buckets

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 152 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextHard

How does Dijkstra's algorithm work?

Continue