295. Find Median from Data Stream

Difficulty:
Related Topics:
Similar Questions:

Problem

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

Implement the MedianFinder class:

  Example 1:

Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]

Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0

  Constraints:

  Follow up:

Solution (Java)

class MedianFinder {
        /*
Key points to solve this problem :-
- > create max heap for smaller half of the list
- > create min heap for the larger half of the list
- > check the size of the two heaps, if they differ by more the 1 element, rebalace them by transfering 1 element from heap with greater size to smaller
-> if the two heaps has equal sizes, median will be average of top element of min and the max heap
- > else if whichever heaps has the max no. of elements, top element of that heap will be the median
    */


    PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
    PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(Collections.reverseOrder());
    public MedianFinder() {

    }
    public void addNum(int num) {
        if(maxHeap.size() == 0 || maxHeap.peek() >= num){
            maxHeap.add(num);
        }
        else{
            minHeap.add(num);
        }
        if(maxHeap.size() > minHeap.size() + 1){
            minHeap.add(maxHeap.poll());
        }
        if(minHeap.size() > maxHeap.size() + 1){
            maxHeap.add(minHeap.poll());
        }
    }

    public double findMedian() {
       double median = 0.0;
       if(minHeap.size() > maxHeap.size()){
           median = minHeap.peek();
       }else if(maxHeap.size() > minHeap.size()){
           median = maxHeap.peek();
       }else{
           median = (minHeap.peek() + maxHeap.peek())/2.0;
       }
      return median;
    }
}

Solution (Javascript)

var MedianFinder = function() {
  this.maxHeap = Heap((a, b) => b - a)
  this.minHeap = Heap((a, b) => a - b)
  this.size = 0
};

/** 
 * @param {number} num
 * @return {void}
 */
MedianFinder.prototype.addNum = function(num) {
  this.size += 1
  const min = this.minHeap.top()
  if (num > min) {
    this.minHeap.insert(num)
    while (this.minHeap.size() > this.maxHeap.size()) { // balance Heaps
      this.maxHeap.insert(this.minHeap.extract())
    }
  } else {
    this.maxHeap.insert(num)
    while (this.maxHeap.size() > this.minHeap.size() + 1) { // balance Heaps
      this.minHeap.insert(this.maxHeap.extract())
    }
  }
};

/**
 * @return {number}
 */
MedianFinder.prototype.findMedian = function() {
  if (this.size > 0) {
    if (this.size % 2 === 0) {
      return (this.maxHeap.top() + this.minHeap.top()) / 2
    }
    return this.maxHeap.top()
  }
  return undefined
};

/** 
 * Your MedianFinder object will be instantiated and called as such:
 * var obj = new MedianFinder()
 * obj.addNum(num)
 * var param_2 = obj.findMedian()
 */

const Heap = (compare) => {
  const list = []
  const parent = index => Math.floor((index - 1) / 2)
  const left = index => 2 * index + 1
  const right = index => 2 * index + 2
  const swap = (a, b) => {
    const temp = list[a]
    list[a] = list[b]
    list[b] = temp
  }
  const insert = (x) => {
    list.push(x)
    let currentIndex = list.length - 1
    let parentIndex = parent(currentIndex)
    while (compare(list[parentIndex], list[currentIndex]) > 0) {
      swap(parentIndex, currentIndex)
      currentIndex = parentIndex
      parentIndex = parent(parentIndex)
    }
  }
  const size = () => list.length
  const top = () => list[0]
  const sink = (index) => {
    let currentIndex = index
    const leftIndex = left(index)
    const rightIndex = right(index)
    if (compare(list[currentIndex], list[leftIndex]) > 0) {
      currentIndex = leftIndex
    }
    if (compare(list[currentIndex], list[rightIndex]) > 0) {
      currentIndex = rightIndex
    }
    if (currentIndex !== index) {
      swap(index, currentIndex)
      sink(currentIndex)
    }
  }
  const extract = () => {
    swap(0, list.length - 1)
    const result = list.pop()
    sink(0)
    return result
  }
  return {
    list,
    size,
    top,
    insert,
    extract,
  }
}

Explain:

nope.

Complexity: