Skip to content
Programming101
Programming101

Learn everything about programming

  • Home
  • CS Subjects
    • IoT – Internet of Things
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programming101
Programming101

Learn everything about programming

Leetcode Find Median from Data Stream problem solution

YASH PAL, 31 July 2024

In this Leetcode Find Median from Data Stream problem solution, 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.

For example, for arr = [2,3,4], the median is 3.

For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.

Implement the MedianFinder class:

  1. MedianFinder() initializes the MedianFinder object.
  2. void addNum(int num) adds the integer num from the data stream to the data structure.

double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.

Leetcode Find Median from Data Stream problem solution

Problem solution in Python.

class MedianFinder:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.maxHeap = []
        self.minHeap = []
        self.median = 0.0
    
    def addNum(self, num: int) -> None:
        if num >= self.median:
            heapq.heappush(self.minHeap, num)
        else:
            heapq.heappush(self.maxHeap,( -1 * num))
        if abs(len(self.maxHeap) - len(self.minHeap)) > 1:
            if len(self.maxHeap) > len(self.minHeap):
                n = heapq.heappop(self.maxHeap)
                n = -1 * n
                heapq.heappush(self.minHeap, n)
            else:
                n = heapq.heappop(self.minHeap)
                heapq.heappush(self.maxHeap, (-1 * n))
        if len(self.maxHeap) > len(self.minHeap):
            self.median = -1 * self.maxHeap[0]
        elif len(self.maxHeap) < len(self.minHeap):
            self.median = self.minHeap[0]
        else:
            self.median = (self.minHeap[0] + (-1 * self.maxHeap[0])) / 2
    
    def findMedian(self) -> float:
        return self.median

Problem solution in Java.

class MedianFinder {
    Queue<Integer> upHeap;
    Queue<Integer> downHeap;
    public MedianFinder() {
        upHeap = new PriorityQueue<>((a, b) -> b-a);
        downHeap = new PriorityQueue<>();
    }

    public void addNum(int num) {
        if(upHeap.size() == 0){
            upHeap.offer(num);
            return;
        }
        if(upHeap.size() > downHeap.size()){
            if(num <= upHeap.peek()){
                upHeap.offer(num);
                downHeap.offer(upHeap.poll());
            }
            else{
                downHeap.offer(num);
            }
        }
        else{
            if(num <= upHeap.peek()){
                upHeap.offer(num);
            }
            else{
                downHeap.offer(num);
                upHeap.offer(downHeap.poll());
            }
        }
    }
    
    public double findMedian() {
        if(upHeap.size() > downHeap.size()){
            return upHeap.peek();
        }
        else{
            return (upHeap.peek() + downHeap.peek()) / 2.0;
        }
    }
}

Problem solution in C++.

class MedianFinder {
public:
    /** initialize your data structure here. */
    //create 1 Max Heap and 1 Min Heap
    priority_queue<int> maxHeap;
    priority_queue<int, vector<int>,greater<int> > minHeap;
    int s1 , s2;
    MedianFinder() {
    }
    
    void addNum(int num) {
        if(maxHeap.empty()) {
            maxHeap.push(num);
        } else if(num > maxHeap.top()) {
            minHeap.push(num);
        } else {
            maxHeap.push(num);
        }
        if(abs((int)maxHeap.size() - (int)minHeap.size()) > 1 ) {
            int ele;
            if(maxHeap.size() > minHeap.size()) {
                ele = maxHeap.top();
                maxHeap.pop();
                minHeap.push(ele);
            } else {
                ele = minHeap.top();
                minHeap.pop();
                maxHeap.push(ele);
            }

        }
    }
    
    double findMedian() {
        s1 = maxHeap.size(),
        s2 = minHeap.size();
        if((s1 + s2) % 2 == 0) {
            double ans = ((double)maxHeap.top() + (double)minHeap.top() ) / (double)2;
            return ans;
        } else {
            if(s1 > s2)
                return maxHeap.top();
            else 
                return minHeap.top();
        }
    }
};

coding problems

Post navigation

Previous post
Next post
  • HackerRank Separate the Numbers solution
  • How AI Is Revolutionizing Personalized Learning in Schools
  • GTA 5 is the Game of the Year for 2024 and 2025
  • Hackerrank Day 5 loops 30 days of code solution
  • Hackerrank Day 6 Lets Review 30 days of code solution
How to download udemy paid courses for free

Pages

  • About US
  • Contact US
  • Privacy Policy

Programing Practice

  • C Programs
  • java Programs

HackerRank Solutions

  • C
  • C++
  • Java
  • Python
  • Algorithm

Other

  • Leetcode Solutions
  • Interview Preparation

Programming Tutorials

  • DSA
  • C

CS Subjects

  • Digital Communication
  • Human Values
  • Internet Of Things
©2025 Programming101 | WordPress Theme by SuperbThemes