...

/

Find the Median of a Number Stream (medium)

Find the Median of a Number Stream (medium)

Problem Statement

Design a class to calculate the median of a number stream. The class should have the following two methods:

  1. insertNum(int num): stores the number in the class
  2. findMedian(): returns the median of all numbers inserted in the class

If the count of numbers inserted in the class is even, the median will be the average of the middle two numbers.

Example 1:

1. insertNum(3)
2. insertNum(1)
3. findMedian() -> output: 2
4. insertNum(5)
5. findMedian() -> output: 3
6. insertNum(4)
7. findMedian() -> output: 3.5

Try it yourself

Try solving this question here:

import java.util.*;
class MedianOfAStream {
public void insertNum(int num) {
// TODO: Write your code here
}
public double findMedian() {
// TODO: Write your code here
return -1;
}
public static void main(String[] args) {
MedianOfAStream medianOfAStream = new MedianOfAStream();
medianOfAStream.insertNum(3);
medianOfAStream.insertNum(1);
System.out.println("The median is: " + medianOfAStream.findMedian());
medianOfAStream.insertNum(5);
System.out.println("The median is: " + medianOfAStream.findMedian());
medianOfAStream.insertNum(4);
System.out.println("The median is: " + medianOfAStream.findMedian());
}
}

Solution

As we know, the median is the middle value in an ordered integer list. So a brute force solution could be to maintain a sorted list of all numbers inserted in the class so that we can efficiently return the median whenever required. Inserting a number in a sorted list will take O(N)O(N) time if there are ‘N’ numbers in the list. This insertion will be similar to the Insertion sort. Can we do better than this? Can we utilize the fact that we don’t need the fully sorted list - we are only interested in finding the middle element?

Assume ‘x’ is the median of a list. This means that half of the numbers in the list will be smaller than (or equal to) ‘x’ and half will be greater than (or equal to) ‘x’. This leads us to an approach where we can divide the list into two halves: one half ...