Practice
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Frontend UI Machine Coding
Resources
Career Advice and Roadmaps
Data Structures and Algorithms
Machine Coding Round (LLD)
System Design & Architecture (HLD)
Backend Development
Frontend Development
Project Ideas for Software Developers
Core Computer Science
Companies
SDE Jobs & Internships
Interview Questions
Compare Companies
IDE
Online IDE
Collaborative IDE

Median From Data Stream Editorial

DSA Editorial, Solution and Code

Practice Problem Link: Median From Data Stream

Please make sure to try solving the problem yourself before looking at the editorial.

Problem Statement

The median of a finite list of numbers is the "middle" number when those numbers are sorted. If the size of the list is even, the median is the average of the two middle numbers.

You have an incoming stream of integers, you need to be able to find the median at any point in time.

Implement the MedianCalculator class:

  • MedianCalculator() initializes the MedianCalculator object and is called at the beginning.
  • void addNum(int num) adds the integer num from the data stream.
  • float getMedian() returns the median of all elements so far.

getMedian will be called only after at least one number has been added.

Naive Approach

In the naive approach, we can naively keep storing the elements in a dynamic array, and keep sorting the array and calculating the median naively according to the given formula, each time the getMedian() function is called.

Analysis

  • Time Complexity: addNum() -> O(1), getMedian() -> O(n * logn).
  • Space Complexity: addNum() ->O(n), getMedian() -> O(n).

Implementation

C++ 

class MedianCalculator {
public:
    /** initialize your data structure here. */
	vector<int> elements;
    MedianCalculator() {
		elements.clear();
    }
    
    void addNum(int num) {
		elements.push_back(num);
    }
    
    float getMedian() {
		vector<int> aux = elements;
		sort(aux.begin(), aux.end());
		if(aux.size() % 2 == 0) {
			return (aux[aux.size() / 2] + aux[aux.size() / 2 - 1]) / 2.0;
		}
		else {
			return (float)aux[aux.size() / 2];
		}
    }
};

/**
 * Your MedianCalculator object will be instantiated and called as such:
 * MedianCalculator* obj = new MedianCalculator();
 * obj->addNum(num);
 * float median = obj->getMedian();
 */
Java
class MedianCalculator {
    /** initialize your data structure here. */
	ArrayList<Integer> elements;
    public MedianCalculator() {
		elements = new ArrayList<>();
    }
    
    public void addNum(int num) {
		elements.add(num);
    }
    
    public float getMedian() {
		Collections.sort(elements);
		int n = elements.size();
		if(n % 2 == 0) {
			int median1 = elements.get(n / 2 - 1);
			int median2 = elements.get(n / 2);
			return (median1 + median2 + 0.0f) / 2.0f;
		}
		else {
			return (float)elements.get(n / 2);
		}
    }
}

/**
 * Your MedianCalculator object will be instantiated and called as such:
 * MedianCalculator obj = new MedianCalculator();
 * obj.addNum(num);
 * float median = obj.getMedian();
 */

Optimal Approach

In the optimal approach, we can use two heaps, one max heap, and a min-heap. One heap will store the larger half of the array, and the other heap will store the smaller half of the array in descending order. When the current length is even, we take the top elements of both the heaps and take their average. Else, we return the top of the appropriate heap as the median. It can also be solved in an easier way in C++ using ordered_set data structure. Refer Implementation for better understanding.

Analysis

  • Time Complexity: addNum() -> O(logn), getMedian() -> O(logn).
  • Space Complexity: addNum() -> O(n), getMedian() -> O(n).

Implementation

C++
class MedianCalculator {
public:
    /** initialize your data structure here. */
	priority_queue<int> large;
	priority_queue<int, vector<int>, greater<int>> small;
    MedianCalculator() {
		while(!large.empty()) {
			large.pop();
		}
		while(!small.empty()) {
			small.pop();
		}
    }
    
    void addNum(int num) {
		large.push(num);
        small.push(large.top());
		large.pop();
        if(large.size() < small.size()) {
            large.push(small.top());
			small.pop();
        }
    }
    
    float getMedian() {
		return large.size() > small.size() ? large.top() : (large.top() + small.top()) / 2.0f;
    }
};

/**
 * Your MedianCalculator object will be instantiated and called as such:
 * MedianCalculator* obj = new MedianCalculator();
 * obj->addNum(num);
 * float median = obj->getMedian();
 */
Java
class MedianCalculator {
    /** initialize your data structure here. */
	PriorityQueue<Integer> small, large;
    public MedianCalculator() {
		small = new PriorityQueue<>((a,b) -> b-a);
        large = new PriorityQueue<>();
    }
    
    public void addNum(int num) {
		large.add(num);
        small.add(large.poll());
        if(large.size() < small.size()) {
            large.add(small.poll());
        }
    }
    
    public float getMedian() {
		return large.size() > small.size() ? large.peek() : (large.peek() + small.peek()) / 2.0f;
    }
}

/**
 * Your MedianCalculator object will be instantiated and called as such:
 * MedianCalculator obj = new MedianCalculator();
 * obj.addNum(num);
 * float median = obj.getMedian();
 */
Related Content
Kth Largest Element From Data Stream
Merge K Sorted Arrays
Sort Almost Sorted Array
SDE Bootcamp - Become a software engineer at a product-based company
Practice Data Structures & Algorithms
Learning Resources
Interview Prep Resources
Community
Join our community
Blog
  • Career Advice and Roadmaps
  • Data Structures & Algorithms
  • Machine Coding Round (LLD)
  • System Design & Architecture
  • Backend Development
  • Frontend Development
  • Awesome Project Ideas
  • Core Computer Science
Practice Questions
  • Machine Coding (LLD) Questions
  • System Design (HLD) Questions
  • Topic-wise DSA Questions
  • Company-wise DSA Questions
  • DSA Sheets (Curated Lists)
  • JavaScript Interview Questions
  • Frontend UI Machine Coding Questions
Online Compilers (IDE)
  • Online Java Compiler
  • Online C++ Compiler
  • Online C Compiler
  • Online Python Compiler
  • Online JavaScript Compiler
Topic-wise Problems
  • Dynamic Programming Interview Questions
  • Linked List Interview Questions
  • Graph Interview Questions
  • Backtracking Interview Questions
  • Arrays Interview Questions
  • Trees Interview Questions
Company-wise Problems
  • Amazon Interview Questions
  • Microsoft Interview Questions
  • Google Interview Questions
  • Flipkart Interview Questions
  • Adobe Interview Questions
  • Facebook Interview Questions
DSA Sheets (Curated Lists)
  • Top Interview Questions
  • FAANG Interview Questions
  • Most Asked Interview Questions
  • 6 month DSA Practice Sheet
  • 3 month DSA Practice Sheet
  • Last minute DSA Practice Sheet