Stacks & heapsLeetCode 295

Lesson 58 of 76

Find Median from Data Stream

Design a structure that accepts a stream of numbers and returns the current median.

Watch on YouTube

Lesson notes

Try it before you watch

Restate the problem in your own words, list the edge cases, and sketch a solution with its running time. Then play the video and compare.

Reveal the key idea

Keep the smaller half in a max-heap and the larger half in a min-heap with balanced sizes; the median comes from the heap tops.

Pattern: Stacks & heaps. Stacks match the most recent item; heaps keep the smallest or largest item one pop away.

Complexity

Cost of the standard optimal approach for Find Median from Data Stream
Measure Bound
Time O(log n) to add, O(1) for the median
Extra space O(n)

Walkthroughs often start from a simpler approach first; aim to reach these bounds. New to Big-O? Read understanding algorithmic complexity.