KatInterview

295. Find Median from Data Stream

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to design a data structure that can efficiently handle two operations: adding a number from a data stream and finding the median of all numbers added so far. The stream nature of the input means we need a dynamic structure that updates efficiently as new numbers arrive.

Solution

Find Median from Data Stream in Python

import heapq

class MedianFinder:

    def __init__(self):
        # Python's heapq is a min-heap. We use it for the 'large' half.
        self.large = []
        # To simulate a max-heap for the 'small' half, we store negated numbers.
        self.small = []

    def addNum(self, num: int) -> None:
        # Add the negated number to the 'small' heap (max-heap)
        heapq.heappush(self.small, -1 * num)
        
        # Balance by moving the largest from 'small' to 'large'
        # The largest in 'small' is the smallest negated number.
        # This ensures every number in 'small' is <= every number in 'large'
        heapq.heappush(self.large, -1 * heapq.heappop(self.small))
        
        # Balance the sizes of the two heaps
        # We want 'small' to have equal or one more element than 'large'
        if len(self.small) < len(self.large):
            heapq.heappush(self.small, -1 * heapq.heappop(self.large))

    def findMedian(self) -> float:
        # If total numbers are odd, the median is the top of the 'small' heap
        if len(self.small) > len(self.large):
            return -1 * self.small[0]
        # If total numbers are even, the median is the average of the tops of both heaps
        else:
            return (-1 * self.small[0] + self.large[0]) / 2


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

Find Median from Data Stream in Java

class MedianFinder {
    // max-heap to store the smaller half of the numbers
    private PriorityQueue<Integer> small;
    // min-heap to store the larger half of the numbers
    private PriorityQueue<Integer> large;

    public MedianFinder() {
        // In Java, PriorityQueue is a min-heap by default.
        // To create a max-heap, we use Collections.reverseOrder().
        small = new PriorityQueue<>(Collections.reverseOrder());
        large = new PriorityQueue<>();
    }
    
    public void addNum(int num) {
        // Add to the max-heap (small half)
        small.add(num);
        
        // Balance by moving the largest from small to large
        // This ensures every number in 'small' is <= every number in 'large'
        large.add(small.poll());
        
        // Balance the sizes of the two heaps
        // We want 'small' to have equal or one more element than 'large'
        if (small.size() < large.size()) {
            small.add(large.poll());
        }
    }
    
    public double findMedian() {
        // If total numbers are odd, the median is the top of the 'small' heap
        if (small.size() > large.size()) {
            return small.peek();
        }
        // If total numbers are even, the median is the average of the tops of both heaps
        else {
            return (small.peek() + large.peek()) / 2.0;
        }
    }
}

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

Find Median from Data Stream in C++

class MedianFinder {
private:
    // max-heap to store the smaller half of the numbers
    priority_queue<int> small;
    // min-heap to store the larger half of the numbers
    priority_queue<int, vector<int>, greater<int>> large;

public:
    MedianFinder() {
        
    }
    
    void addNum(int num) {
        // Add to the max-heap (small half)
        small.push(num);
        
        // Balance by moving the largest from small to large
        // This ensures every number in 'small' is <= every number in 'large'
        large.push(small.top());
        small.pop();
        
        // Balance the sizes of the two heaps
        // We want 'small' to have equal or one more element than 'large'
        if (small.size() < large.size()) {
            small.push(large.top());
            large.pop();
        }
    }
    
    double findMedian() {
        // If total numbers are odd, the median is the top of the 'small' heap
        if (small.size() > large.size()) {
            return small.top();
        }
        // If total numbers are even, the median is the average of the tops of both heaps
        else {
            return (small.top() + large.top()) / 2.0;
        }
    }
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */

Find Median from Data Stream in TypeScript

class MinHeap {
    private heap: number[];

    constructor() {
        this.heap = [];
    }

    size(): number {
        return this.heap.length;
    }

    peek(): number | null {
        return this.heap.length > 0 ? this.heap[0] : null;
    }

    push(val: number): void {
        this.heap.push(val);
        this.siftUp(this.heap.length - 1);
    }

    pop(): number | null {
        if (this.size() <= 0) return null;
        this.swap(0, this.size() - 1);
        const val = this.heap.pop();
        if (this.size() > 0) this.siftDown(0);
        return val as number;
    }

    private parent(i: number): number {
        return Math.floor((i - 1) / 2);
    }

    private leftChild(i: number): number {
        return 2 * i + 1;
    }

    private swap(i: number, j: number): void {
        [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
    }

    private siftUp(i: number): void {
        let p = this.parent(i);
        while (i > 0 && this.heap[i] < this.heap[p]) {
            this.swap(i, p);
            i = p;
            p = this.parent(i);
        }
    }

    private siftDown(i: number): void {
        let minIndex = i;
        const l = this.leftChild(i);
        const r = 2 * i + 2; // right child
        if (l < this.size() && this.heap[l] < this.heap[minIndex]) {
            minIndex = l;
        }
        if (r < this.size() && this.heap[r] < this.heap[minIndex]) {
            minIndex = r;
        }
        if (i !== minIndex) {
            this.swap(i, minIndex);
            this.siftDown(minIndex);
        }
    }
}

class MedianFinder {
    private small: MinHeap; // Max-heap simulated with a min-heap storing negative numbers
    private large: MinHeap; // Min-heap

    constructor() {
        this.small = new MinHeap();
        this.large = new MinHeap();
    }

    addNum(num: number): void {
        // Add negated number to 'small' heap (max-heap)
        this.small.push(-num);

        // Balance by moving the largest from 'small' to 'large'
        const valToMove = this.small.pop();
        if (valToMove !== null) {
            this.large.push(-valToMove);
        }

        // Balance the sizes of the two heaps
        if (this.small.size() < this.large.size()) {
            const valToBalance = this.large.pop();
            if (valToBalance !== null) {
                this.small.push(-valToBalance);
            }
        }
    }

    findMedian(): number {
        if (this.small.size() > this.large.size()) {
            // Total numbers are odd, median is top of 'small' heap
            return -this.small.peek()!;
        } else {
            // Total numbers are even, median is average of tops of both heaps
            const smallTop = -this.small.peek()!;
            const largeTop = this.large.peek()!;
            return (smallTop + largeTop) / 2;
        }
    }
}

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

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.