Find the running median hackerrank solution

Given that integers are read from a data stream. Find median of elements read so for in an efficient way. For simplicity assume, there are no duplicates. For example, let us consider the stream 5, 15, 1, 3 … 
 

After reading 1st element of stream - 5 -> median - 5 After reading 2nd element of stream - 5, 15 -> median - 10 After reading 3rd element of stream - 5, 15, 1 -> median - 5 After reading 4th element of stream - 5, 15, 1, 3 -> median - 4, so on...

Making it clear, when the input size is odd, we take the middle element of sorted data. If the input size is even, we pick the average of the middle two elements in the sorted stream.
Note that output is the effective median of integers read from the stream so far. Such an algorithm is called an online algorithm. Any algorithm that can guarantee the output of i-elements after processing i-th element, is said to be online algorithm. Let us discuss three solutions to the above problem.

Method 1: Insertion Sort

If we can sort the data as it appears, we can easily locate the median element. Insertion Sort is one such online algorithm that sorts the data appeared so far. At any instance of sorting, say after sorting i-th element, the first i elements of the array are sorted. The insertion sort doesn’t depend on future data to sort data input till that point. In other words, insertion sort considers data sorted so far while inserting the next element. This is the key part of insertion sort that makes it an online algorithm.

However, insertion sort takes O(n2) time to sort n elements. Perhaps we can use binary search on insertion sort to find the location of the next element in O(log n) time. Yet, we can’t do data movement in O(log n) time. No matter how efficient the implementation is, it takes polynomial time in case of insertion sort.
Interested readers can try the implementation of Method 1.



int binarySearch(int arr[], int item, int low, int high)

        return (item > arr[low]) ? (low + 1) : low;

    int mid = (low + high) / 2;

        return binarySearch(arr, item, mid + 1, high);

    return binarySearch(arr, item, low, mid - 1);

void printMedian(int arr[], int n)

    cout << "Median after reading 1"

         << " element is " << arr[0] << "\n";

    for (i = 1; i < n; i++) {

        pos = binarySearch(arr, num, 0, j);

            median = (arr[(count / 2) - 1] + arr[count / 2])

        cout << "Median after reading " << i + 1

             << " elements is " << median << "\n";

    int arr[] = { 5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 };

    int n = sizeof(arr) / sizeof(arr[0]);

  static int binarySearch(int arr[], int item, int low, int high)

      return (item > arr[low]) ? (low + 1) : low;

    int mid = (low + high) / 2;

      return binarySearch(arr, item, mid + 1, high);

    return binarySearch(arr, item, low, mid - 1);

  static void printMedian(int arr[], int n)

    System.out.println( "Median after reading 1"

                       + " element is " + arr[0]);

    for (i = 1; i < n; i++) {

      pos = binarySearch(arr, num, 0, j);

        median = (arr[(count / 2) - 1] + arr[count / 2])

      System.out.println( "Median after reading " + (i + 1)

                         + " elements is " + (int)median );

  public static void main (String[] args) {

    int arr[] = { 5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 };

def binarySearch(arr, item, low, high):

        return (low + 1) if (item > arr[low]) else low

        return binarySearch(arr, item, mid + 1, high)

    return binarySearch(arr, item, low, mid - 1)

    i, j, pos, num = 0, 0, 0, 0

    print(f"Median after reading 1 element is {arr[0]}")

        pos = binarySearch(arr, num, 0, j)

            median = (arr[(count // 2) - 1] + arr[count // 2]) // 2

        print(f"Median after reading {i + 1} elements is {median} ")

if __name__ == "__main__":

    arr = [5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4]

  static int binarySearch(int[] arr, int item, int low, int high)

      return (item > arr[low]) ? (low + 1) : low;

    int mid = (low + high) / 2;

      return binarySearch(arr, item, mid + 1, high);

    return binarySearch(arr, item, low, mid - 1);

  static void printMedian(int[] arr, int n)

    Console.WriteLine( "Median after reading 1"

                       + " element is " + arr[0]);

    for (i = 1; i < n; i++) {

      pos = binarySearch(arr, num, 0, j);

        median = (arr[(count / 2) - 1] + arr[count / 2])

      Console.WriteLine( "Median after reading " + (i + 1)

                         + " elements is " + (int)median );

public static void Main(String[] args)

    int[] arr = { 5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 };

    const binarySearch = (arr, item, low, high) => {

            return (item > arr[low]) ? (low + 1) : low;

        let mid = parseInt((low + high) / 2);

            return binarySearch(arr, item, mid + 1, high);

        return binarySearch(arr, item, low, mid - 1);

    const printMedian = (arr, n) => {

        document.write(`Median after reading 1 element is ${arr[0]}
`);

        for (i = 1; i < n; i++) {

            pos = binarySearch(arr, num, 0, j);

                median = arr[parseInt(count / 2)];

                median = parseInt((arr[parseInt(count / 2) - 1] + arr[parseInt(count / 2)]) / 2);

            document.write(`Median after reading ${i + 1} elements is ${median}
`);

    let arr = [5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4];

Output Median after reading 1 element is 5 Median after reading 2 elements is 10 Median after reading 3 elements is 5 Median after reading 4 elements is 4 Median after reading 5 elements is 3 Median after reading 6 elements is 4 Median after reading 7 elements is 5 Median after reading 8 elements is 6 Median after reading 9 elements is 7 Median after reading 10 elements is 6 Median after reading 11 elements is 7 Median after reading 12 elements is 6

Time Complexity: O(n2)
Space Complexity: O(1)

Method 2: Augmented self-balanced binary search tree (AVL, RB, etc…)
At every node of BST, maintain a number of elements in the subtree rooted at that node. We can use a node as the root of a simple binary tree, whose left child is self-balancing BST with elements less than root and right child is self-balancing BST with elements greater than root. The root element always holds effective median.

If the left and right subtrees contain a same number of elements, the root node holds the average of left and right subtree root data. Otherwise, the root contains the same data as the root of subtree which is having more elements. After processing an incoming element, the left and right subtrees (BST) are differed utmost by 1.

Self-balancing BST is costly in managing the balancing factor of BST. However, they provide sorted data which we don’t need. We need median only. The next method makes use of Heaps to trace the median.

Method 3: Heaps
Similar to balancing BST in Method 2 above, we can use a max heap on the left side to represent elements that are less than effective median, and a min-heap on the right side to represent elements that are greater than effective median.

After processing an incoming element, the number of elements in heaps differs utmost by 1 element. When both heaps contain the same number of elements, we pick the average of heaps root data as effective median. When the heaps are not balanced, we select effective median from the root of the heap containing more elements.

Given below is the implementation of the above method. For the algorithm to build these heaps, please read the highlighted code.

#define MAX_HEAP_SIZE (128)

#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])

void Exch(int &a, int &b)

bool Greater(int a, int b)

bool Smaller(int a, int b)

int Average(int a, int b)

    Heap(int *b, bool (*c)(int, int)) : A(b), comp(c)

    virtual bool Insert(int e) = 0;

    virtual int  GetTop() = 0;

    virtual int  ExtractTop() = 0;

    virtual int  GetCount() = 0;

        if( p >= 0 && comp(A[i], A[p]) )

            heapify(parent(heapSize+1));

    bool insertHelper(int key)

        if( heapSize < MAX_HEAP_SIZE )

class MaxHeap : public Heap

    MaxHeap() : Heap(new int[MAX_HEAP_SIZE], &Greater)  {  }

        return insertHelper(key);

class MinHeap : public Heap

    MinHeap() : Heap(new int[MAX_HEAP_SIZE], &Smaller) { }

        return insertHelper(key);

int getMedian(int e, int &m, Heap &l, Heap &r)

    int sig = Signum(l.GetCount(), r.GetCount());

            r.Insert(l.ExtractTop());

        m = Average(l.GetTop(), r.GetTop());

            l.Insert(r.ExtractTop());

        m = Average(l.GetTop(), r.GetTop());

void printMedian(int A[], int size)

    Heap *left  = new MaxHeap();

    Heap *right = new MinHeap();

    for(int i = 0; i < size; i++)

        m = getMedian(A[i], m, *left, *right);

    int A[] = {5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4};

    int size = ARRAY_SIZE(A);

from heapq import heappush, heappop, heapify

    heappush(minHeap,-heappop(maxHeap))   

    if len(minHeap) > len(maxHeap):

        heappush(maxHeap,-heappop(minHeap))

    if len(minHeap)!= len(maxHeap):

        return (minHeap[0]- maxHeap[0])/2

if __name__== '__main__':

    A= [5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4]

        print(math.floor(getMedian()))

Time Complexity: If we omit the way how stream was read, complexity of median finding is O(N log N), as we need to read the stream, and due to heap insertions/deletions.

Auxiliary Space: O(N)
At first glance the above code may look complex. If you read the code carefully, it is simple algorithm. 

Median of Stream of Running Integers using STL