Skip to content
Decoder

Running Median

Hard

Problem

Build a class MedianFinder that takes numbers one at a time and can report the median of everything added so far.

- add_num(num) (addNum in TypeScript) adds an integer. - find_median() (findMedian) returns the median: the middle value if the count is odd, or the average of the two middle values if it is even.

Example 1

m = MedianFinder()

Example 2

m.add_num(1)

Example 3

m.add_num(2)

Example 4

Input
m.find_median()
Output
1.5

Example 5

m.add_num(3)

Example 6

Input
m.find_median()
Output
2

Both methods should be fast; sorting on every call is too slow.

Constraints

  • -10^5 <= num <= 10^5
  • At most 5 * 10^4 calls are made in total.
  • find_median is only called after at least one number has been added.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.