Find median in a stream | Practice | GeeksforGeeks

Given an input stream of N integers. The task is to insert these numbers into a new stream and find the median of the stream formed by each insertion of X to the new stream.
Example 1:
Input:
N = 4
X[] = 5,15,1,3
Output:
5
10
5
4
Explanation:Flow in stream : 5, 15, 1, 3 
5 goes to stream --> median 5 (5) 
15 goes to stream --> median 10 (5,15) 
1 goes to stream --> median 5 (5,15,1) 
3 goes to stream --> median 4 (5,15,1 3) 

 
Example 2:
Input:
N = 3
X[] = 5,10,15
Output:
5
7.5
10
Explanation:Flow in stream : 5, 10, 15
5 goes to stream --> median 5 (5) 
10 goes to stream --> median 7.5 (5,10) 
15 goes to stream --> median 10 (5,10,15) 


insertHeap() which takes x as input and inserts it into the heap, the function should then call balanceHeaps() to balance the new heap.
balanceHeaps() does not take any arguments. It is supposed to balance the two heaps.
getMedian() does not take any arguments. It should return the current median of the stream.

insertHeap() which takes x as input and inserts it into the heap, the function should then call balanceHeaps() to balance the new heap.
balanceHeaps() does not take any arguments. It is supposed to balance the two heaps.
getMedian() does not take any arguments. It should return the current median of the stream.
0
hharshit81182 weeks ago
class Solution:
{   public:   priority_queue<int> pq1;   priority_queue<int, vector<int>, greater<int>> pq2;   void insertHeap(int &x)   {       if(pq1.empty() == true){           pq1.push(x);           return;       }       if(pq1.size() > pq2.size()){           if(pq1.top() > x){               pq2.push(pq1.top());               pq1.pop();               pq1.push(x);           }           else{               pq2.push(x);           }       }       else{           if(pq2.top() < x){               pq1.push(pq2.top());               pq2.pop();               pq2.push(x);           }           else{               pq1.push(x);           }       }   }   double getMedian()   {       if(pq1.size() == pq2.size()){           return (double)(pq1.top()+pq2.top())/ 2;       }       else{           return (double)pq1.top();       }   }};
0
joyrockok1 month ago
class Solution{   static public class decreaseComp implements Comparator<Integer> { @Override public int compare(Integer o1, Integer o2) {  // TODO Auto-generated method stub  if(o1 < o2)   return 1;  else if (o1 > o2)   return -1;  else   return 0; }   }      static decreaseComp dComp = new decreaseComp();      static PriorityQueue<Integer> minQueue = new PriorityQueue<Integer>();   static PriorityQueue<Integer> maxQueue = new PriorityQueue<Integer>(dComp);     static int maxQ=0, minQ=0;   //Function to insert heap.  public static void insertHeap(int x)  {       // add your code here    if(maxQueue.isEmpty() == false && x > maxQueue.peek()) {     minQueue.add(x);     minQ++;    } else {     maxQueue.add(x);     maxQ++;    }        balanceHeaps();   }      //Function to balance heaps.   public static void balanceHeaps()   {      // add your code here    int p;    if(minQ >= maxQ+1) {     p = minQueue.poll();     minQ--;     maxQueue.add(p);     maxQ++;    } else if (minQ+1 < maxQ) {     p = maxQueue.poll();     maxQ--;     minQueue.add(p);     minQ++;    }   }      //Function to return Median.   public static double getMedian()   {       // add your code here               int oddeven = (maxQ+minQ)%2;              if(oddeven == 1) {        return maxQueue.peek();       } else {        return (maxQueue.peek() + minQueue.peek())/2;       }   }   }
+1
milindprajapatmst191 month ago
class Solution {
public:
    priority_queue<int> q1;
    priority_queue<int, vector<int>, greater<int>> q2;
    void insertHeap(int &x) {
        if (q1.empty() || x <= q1.top())
            q1.push(x);
        else
            q2.push(x);
        balanceHeaps();
    }
    void balanceHeaps() {
        if (q2.size() - q1.size() == 1) {
            q1.push(q2.top());
            q2.pop();
        }
        else if (q1.size() - q2.size() == 2) {
            q2.push(q1.top());
            q1.pop();
        }
    }
    double getMedian() {
        if (q1.size() == q2.size())
            return (q1.top() + q2.top()) / 2.0;
        return q1.top();
    }
};
+1
parthbabbar0011 month ago
Solution in C++
 
class Solution
{
    public:
    priority_queue<double> maxHeap;
    priority_queue<double , vector<double>, greater<double> > minHeap; 
    //Function to insert heap.
    void insertHeap(int &x)
    {
        if(maxHeap.size() == minHeap.size()){
            
            if(maxHeap.size() == 0){
                maxHeap.push(x);
                return ;
            }
            
            if(x < maxHeap.top()){             // if size of x is less maxHEap than push in maxheap  else push in minheap
                maxHeap.push(x);
            }
            else{
                minHeap.push(x);
            }
        }
        else {
            
            // Case 2: If size is differernt
            
            // 1-> if size of maxHEap > minHeap 
            if(maxHeap.size() > minHeap.size()){
                
                if(x < maxHeap.top()){
                    
                    int temp = maxHeap.top();
                    maxHeap.pop();
                    maxHeap.push(x);
                    minHeap.push(temp);
                    
                } else {
                    minHeap.push(x);
                }
                
            }
            else{   // 2 -> if size of minHeap > maxHeap
                
                if(x > minHeap.top()){
                    
                    int temp = minHeap.top();
                    minHeap.pop();
                    minHeap.push(x);
                    maxHeap.push(temp);
                    
                } else{
                    maxHeap.push(x);
                }
            }
        }
    }
    
    //Function to balance heaps.
    void balanceHeaps()
    {
        return ;
    }
    
    //Function to return Median.
    double getMedian()
    {
        if(maxHeap.size() > minHeap.size()){
            return maxHeap.top();
        }
        else if(minHeap.size() > maxHeap.size()){
            return minHeap.top();
        }
        else{
            return (maxHeap.top() + minHeap.top())/2;
        }
    }
};

+1
vedirajnish2 months ago

class Solution
{
    static PriorityQueue<Integer>left = new PriorityQueue<>();
    static PriorityQueue<Integer>right = new PriorityQueue<>(Collections.reverseOrder());
    public static void insertHeap(int x)
    {
        left.add(x);
        right.add(left.peek());
        left.poll();
        balanceHeaps();
    }
    
    //Function to balance heaps.
    public static void balanceHeaps()
    {
       if(right.size()>left.size()){
           left.add(right.peek());
           right.poll();
       }
    }
    
    //Function to return Median.
    public static double getMedian()
    {
        if(left.size()==right.size()){
            int v = left.peek();
            int v1 = right.peek();
            return (double)(v+v1)/2;
        }
        return (double)left.peek();
    }
    
}
+3
shrikantsharma47172 months ago
C++ Simple solution

class Solution
{
    public:
    priority_queue<int>max_lhalf;
    priority_queue<int , vector<int>,greater<int>>min_uhalf;
    //Function to insert heap.
    void insertHeap(int &x)
    {
        if(max_lhalf.empty() || max_lhalf.top()>=x){
            max_lhalf.push(x);
        }else{
            min_uhalf.push(x);
        }
        balanceHeaps();
        
    }
    
    //Function to balance heaps.
    void balanceHeaps()
    {
        if(max_lhalf.size()>min_uhalf.size() && max_lhalf.size() - min_uhalf.size()>1){
            min_uhalf.push(max_lhalf.top());
            max_lhalf.pop();
        }
        else if(min_uhalf.size()>max_lhalf.size() && min_uhalf.size() - max_lhalf.size() >1){
            max_lhalf.push(min_uhalf.top());
            min_uhalf.pop();
        }
    }
    
    //Function to return Median.
    double getMedian()
    {
        double med = 0.0;
        if (max_lhalf.size()!=min_uhalf.size()){
            med = max_lhalf.size() > min_uhalf.size() ? max_lhalf.top():min_uhalf.top();

        }else{
            med = (double) (min_uhalf.top()+max_lhalf.top())/2;
        }
        return med;
    }
};
{
    public:
    priority_queue<int>max_lhalf;
    priority_queue<int , vector<int>,greater<int>>min_uhalf;
    //Function to insert heap.
    void insertHeap(int &x)
    {
        if(max_lhalf.empty() || max_lhalf.top()>=x){
            max_lhalf.push(x);
        }else{
            min_uhalf.push(x);
        }
        balanceHeaps();
        
    }
    
    //Function to balance heaps.
    void balanceHeaps()
    {
        if(max_lhalf.size()>min_uhalf.size() && max_lhalf.size() - min_uhalf.size()>1){
            min_uhalf.push(max_lhalf.top());
            max_lhalf.pop();
        }
        else if(min_uhalf.size()>max_lhalf.size() && min_uhalf.size() - max_lhalf.size() >1){
            max_lhalf.push(min_uhalf.top());
            min_uhalf.pop();
        }
    }
    
    //Function to return Median.
    double getMedian()
    {
        double med = 0.0;
        if (max_lhalf.size()!=min_uhalf.size()){
            med = max_lhalf.size() > min_uhalf.size() ? max_lhalf.top():min_uhalf.top();

        }else{
            med = (double) (min_uhalf.top()+max_lhalf.top())/2;
        }
        return med;
    }
};
```
0
dkpati4312 months ago
static PriorityQueue<Integer> lpq = new PriorityQueue<>(Collections.reverseOrder());
   static PriorityQueue<Integer> rpq = new PriorityQueue<>();
   public static void insertHeap(int x)
   {
       // add your code here
       if(!rpq.isEmpty()&&rpq.peek()<x){
           rpq.add(x);
           balanceHeaps();
       }else{
           lpq.add(x);
           balanceHeaps();
       }
   }
   //Function to balance heaps.
   public static void balanceHeaps()
   {
      // add your code here
      if(lpq.size()-rpq.size()==2){
          rpq.add(lpq.remove());
      }
      else if(rpq.size()-lpq.size()==2){
          lpq.add(rpq.remove());
      } 
   }
   //Function to return Median.
   public static double getMedian()
   {
       // add your code her
       if(rpq.size()==lpq.size())
          return Double.valueOf((lpq.peek()+rpq.peek())/2);
       else if(rpq.size()<lpq.size())
          return Double.valueOf(lpq.peek());
       else
          return Double.valueOf(rpq.peek());
   }
0
himanshukug19cs2 months ago
java solution
 
  static PriorityQueue<Integer> lpq = new PriorityQueue<>(Collections.reverseOrder());   static PriorityQueue<Integer> rpq = new PriorityQueue<>();   public static void insertHeap(int x)   {       // add your code here       if(!rpq.isEmpty()&&rpq.peek()<x){           rpq.add(x);           balanceHeaps();       }else{           lpq.add(x);           balanceHeaps();       }   }   //Function to balance heaps.   public static void balanceHeaps()   {      // add your code here      if(lpq.size()-rpq.size()==2){          rpq.add(lpq.remove());      }      else if(rpq.size()-lpq.size()==2){          lpq.add(rpq.remove());      }    }   //Function to return Median.   public static double getMedian()   {       // add your code her       if(rpq.size()==lpq.size())          return Double.valueOf((lpq.peek()+rpq.peek())/2);       else if(rpq.size()<lpq.size())          return Double.valueOf(lpq.peek());       else          return Double.valueOf(rpq.peek());   }   
0
saurabhsathe12342 months ago
public:
    //Function to insert heap.
    priority_queue<int> s ;
    priority_queue<int , vector<int> , greater<int> > g ;
    void insertHeap(int &x)
    {
        if(s.size() > g.size())
        {
            if( x <= s.top())
            {
                s.push(x);
                g.push(s.top());
                s.pop();
                
            }
            else
                g.push(x);
        }
        else
        {
            if(s.empty() || x <= s.top() )
            {
                s.push(x);
            }
            else
            {
                g.push(x);
                s.push(g.top());
                g.pop();
            }
        }
    }
    
    //Function to balance heaps.
    void balanceHeaps()
    {
        return;
    }
    
    //Function to return Median.
    double getMedian()
    {
        double res;
        if(s.size() == g.size())
        {
            res = s.top()+g.top() ;
            res = res/2;
            
        }
        else
            res = s.top();
            
        return res;
    }
+2
aloksinghbais022 months ago
C++ solution having time complexity as O(N*log(N)) and space complexity as O(N) is as follows :- 
 
Execution Time :- 2.4 / 6.1 sec
 
   private:
   priority_queue<int> pq1; // max heap   priority_queue<int,vector<int>,greater<int>> pq2; // min heap   public:   //Function to insert heap   void insertHeap(int &x)   {       if(pq1.empty() || pq1.top() >= x){           pq1.push(x);       }       else{           pq2.push(x);       }       balanceHeaps();   }      //Function to balance heaps.   void balanceHeaps()   {       if(pq1.size() > pq2.size() && pq1.size() - pq2.size() > 1){           pq2.push(pq1.top());           pq1.pop();       }       else if(pq2.size() > pq1.size() && pq2.size() - pq1.size() > 1){           pq1.push(pq2.top());           pq2.pop();                  }   }      //Function to return Median.   double getMedian()   {       double med = 0.0;       if(pq1.size() != pq2.size()){           med = pq1.size() > pq2.size() ? pq1.top() : pq2.top();       }       else{           med = (double)(pq1.top() + pq2.top()) / 2;       }              return (med);   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.