2dbi
Home/Flipkart/Find Median from a Data Stream
FFlipkart·DSASDE-2Technical Interview – DSA

Find Median from a Data Stream

Problem

Design a data structure that supports:

  • addNum(int num) — add a number from the stream
  • findMedian() — return the median of all numbers added so far

Example

addNum(1), addNum(2) → findMedian() = 1.5
addNum(3)            → findMedian() = 2

Constraints

  • -10^5 ≤ num ≤ 10^5
  • Up to 5 × 10^4 calls

Expected approach

Two heaps: a max-heap for the lower half and a min-heap for the upper half. Rebalance after every insert.

Follow-up

If 99% of numbers are in [0, 100], how would you optimise memory?

added 6 days ago
LeadersAccount