I bet you have some wonderful data structure and algorithm problems that you want to share with the world!


Running Median

Running Median


Find the running median after entering every number from a sequence of infinite integers.

Brute force

If we keep each number in a sorted sequence then cost of single entry is O(n) and finding median is O(n). A slight modification can be done by keeping the middle pointer and adjusting it based on the insertion on its left side and right side. In that case finding median after insertion is O(1). But the overall cost for finding median still remains O(n) as insertion in sorted sequence is necessary after each number is entered.

Better solution

We can keep two heaps which divides the entered number in two almost equal halves. Half of the number would be greater than the median and the rest would be lesser. The upper half will be maintained in a min heap and the lower half will be maintained in a max heap. In this arrangement we can find out in O(1) time whether a new number would go to the upper half or lower half. All we need to do is to compare the new number with the head of two heaps. After deciding we can insert in a heap in O(log n) time. After this insertion if the heaps are unbalanced, we can just move from one heap to another. which is again of O(log n) complexity. And now we can find the median in O(1) time. If two heaps contain same number of elements then median is the average of the head of two heaps. If one is greater, then median is the head of the larger heap.

Further discussion

Whenever the answer of some problem requires knowing greater among something or lesser among something but it does not matter whether the rest of the elements are ordered or not, heap might give the optimal solution.


import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;

public class RunningMedian
    PriorityQueue<Integer> upperQueue;
    PriorityQueue<Integer> lowerQueue;

    public RunningMedian()
        lowerQueue=new PriorityQueue<Integer>(
          20,new Comparator<Integer>()

            public int compare(Integer o1, Integer o2)

                return -o1.compareTo(o2);

        upperQueue=new PriorityQueue<Integer>();

    public double getMedian(int num)
        //adding the number to proper heap
        //balancing the heaps
        else if(lowerQueue.size()-upperQueue.size()==2)
        //returning the median
        else if(upperQueue.size()>lowerQueue.size())
            return upperQueue.peek();
            return lowerQueue.peek();

    public static void main(String[] args)
        Random random=new Random();
        RunningMedian runningMedian=new RunningMedian();
        for(int i=0;i<50;++i)
            int num=random.nextInt(100);