Question

Formatted question description: https://leetcode.ca/all/295.html

Level

Hard

Description

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

For example, [2,3,4], the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

Example:

addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3) 
findMedian() -> 2

Follow up:

  1. If all integer numbers from the stream are between 0 and 100, how would you optimize it?
  2. If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?

Algorithm

Since the data in the data stream is not in order, we should first think of a way to make it in ordered. If we use a vector to save the data stream, we must sort the array every time a new data comes in, which is not efficient.

Use large and small heaps to solve the problem, where the large heap holds the larger numbers in the right half, and the small heap holds the smaller numbers in the left half. In this way, the entire array is divided into two sections in the middle. Since the heap is saved from large to small, we hope that the data in the large pile is from small to large, so it is convenient to take the first one to calculate the median.

Follow up

Q-1: If all integer numbers from the stream are between 0 and 100, how would you optimize it?
  • We can maintain an integer array of length 100 to store the count of each number along with a total count. Then, we can iterate over the array to find the middle value to get our median. Time and space complexity would be O(100) = O(1).
Q-2: If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?
  • In this case, we can keep a counter for lessThanHundred and greaterThanHundred. As we know the solution will be definitely in 0-100 we don’t need to know those number which are >100 or <0, only count of them will be enough.

Code

Java

  • ```java import java.util.*;

    public class Find_Median_from_Data_Stream {

    public static void main(String[] args) {
        Find_Median_from_Data_Stream out = new Find_Median_from_Data_Stream();
        MedianFinder mf = out.new MedianFinder();
    
        mf.addNum(1);
        mf.addNum(2);
        System.out.println( mf.findMedian() ); // 1.5
    
        mf.addNum(3);
        System.out.println( mf.findMedian() ); // 2
    
    }
    
    
    /**
     * Your MedianFinder object will be instantiated and called as such:
     *
     * obj.addNum(num);
     * double param_2 = obj.findMedian();
     */
    
    // ref: https://leetcode.com/problems/find-median-from-data-stream/solution/
    
    class MedianFinder {
    
        PriorityQueue<Integer> smallerHalf; // one more than larger half, or equal to larger half
        PriorityQueue<Integer> largerHalf;
    
        /** initialize your data structure here. */
        public MedianFinder() {
            smallerHalf = new PriorityQueue<Integer>(new MaxComparator());
            largerHalf = new PriorityQueue<Integer>(new MinComparator());
        }
    
        // below addNum() with too many condition checks
        // @note: simple logic: always add to larger half, and if larger half 1 more than smaller half, then re-balance
    
        public void addNum(int num) {
            // 2 polls() and 3 offer(), total 5 operations, each logN => 5 * logN ~= logN
            // https://stackoverflow.com/questions/28819327/time-complexity-of-inserting-in-to-a-heap
    
            // always to smaller half first
            // can check if num bigger than smallerHalf.peek, to directly offer to biggerHalf
            smallerHalf.offer(num);
    
            // now smaller half get additional int, re-balance by smaller half giving its max to smaller half
            largerHalf.offer(smallerHalf.poll());
    
            if (smallerHalf.size() < largerHalf.size()) { // only for the 1st time initial num being added
                smallerHalf.offer(largerHalf.poll());
            }
        }
    
        public double findMedian() {
            if (smallerHalf.size() == largerHalf.size()) {
                return (smallerHalf.peek() + largerHalf.peek()) / 2.0; // @note: double division
            } else { // smaller half is one more
                return smallerHalf.peek();
            }
        }
    
    
        class MaxComparator implements Comparator<Integer> {
    
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1; //max first
            }
        }
    
        class MinComparator implements Comparator<Integer> {
    
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2; // min first
            }
    
        }
    }
    
    
    class MedianFinder_NlogN {
    
        List<Integer> list;
    
        /** initialize your data structure here. */
        public MedianFinder_NlogN() {
            list = new ArrayList<>();
        }
    
        public void addNum(int num) {
            list.add(num);
            Collections.sort(list); // maintain a sorted list
        }
    
        public double findMedian() {
    
            int length = list.size();
    
            if (length % 2 == 1) {
                return list.get(length / 2);
            } else {
                return (list.get(length / 2) + list.get(length / 2 -1)) / 2.0; // @note: if x / 2, then will be an int, 3/2==1, 3/2.0==1.5
            }
        }
    }
    

    }```

  • // OJ: https://leetcode.com/problems/find-median-from-data-stream/
    // Time:
    //      MedianFinder: O(1)
    //      addNum: O(logN)
    //      findMedian: O(1)
    // Space: O(N)
    class MedianFinder {
        priority_queue<int> sm;
        priority_queue<int, vector<int>, greater<>> gt;
    public:
        MedianFinder() {}
        void addNum(int num) {
            if (gt.size() && num > gt.top()) {
                gt.push(num);
                if (gt.size() > sm.size()) {
                    sm.push(gt.top());
                    gt.pop();
                }
            } else {
                sm.push(num);
                if (sm.size() > gt.size() + 1) {
                    gt.push(sm.top());
                    sm.pop();
                }
            }
        }
        double findMedian() {
            return sm.size() > gt.size() ? sm.top() : ((double)sm.top() + gt.top()) / 2;
        }
    };
    
  • from heapq import heappush, heappop
    
    class MedianFinder:
    
    	def __init__(self):
    		self.smallerHalf = [] # the smaller half of the list, max heap (invert min-heap)
    		self.largerHalf = [] # the larger half of the list, min heap
    
    	def addNum(self, num: int) -> None:
    
    		# trick for smaller half, use -1*val
    		# heapq in python does NOT have comparator like in Java
    		heappush(self.smallerHalf, -num)
    		heappush(self.largerHalf, -heappop(self.smallerHalf)) # note: not self.smallerHalf.pop()
    
    		if len(self.smallerHalf) < len(self.largerHalf):
    			heappush(self.smallerHalf, -heappop(self.largerHalf))
    
    	def findMedian(self) -> float:
    		if len(self.smallerHalf) == len(self.largerHalf):
    			return (-self.smallerHalf[0] + self.largerHalf[0]) / 2.0
    		else:
    			return float(-self.smallerHalf[0])
    
    # Your MedianFinder object will be instantiated and called as such:
    # obj = MedianFinder()
    # obj.addNum(num)
    # param_2 = obj.findMedian()
    

All Problems

All Solutions