Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Hard Heap / Priority Queue High frequency Solution Available Practice Mode

Find Median from Data Stream LeetCode Solution

Tags: #Two Heaps #Design #Sorting

Approach Summary

Maintain a max-heap for the lower half and min-heap for the upper half. Balance their sizes; median is the top of the larger or average of both tops.

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Heap / Priority Queue Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Heap / Priority Queue pattern.

Framework: Heap / Priority Queue • Interview Prep: Tested at FAANG • Explore all Heap / Priority Queue problems & invariants →

How to Recognize This Pattern

  • Running median
  • Two heaps pattern

Complexity Analysis

Time Complexity

O(log n) add, O(1) median

Space Complexity

O(n)

Tags

Two Heaps Design Sorting

Frequently Asked Questions

What is the optimal time and space complexity for Find Median from Data Stream?
The optimal solution for Find Median from Data Stream achieves O(log n) add, O(1) median runtime complexity and requires O(n) auxiliary space. Time Complexity: `addNum(num)` takes O(log N) time because pushing and popping from either heap of size N/2 requires logarithmic heap adjustment. `findMedian()` takes O(1) time because the median elements reside directly at the top of the two heaps. Space Complexity is O(N) to store all N incoming numbers across the two heaps.
How do I identify that Find Median from Data Stream requires the Heap / Priority Queue pattern?
In technical interviews, look for key problem signals: Running median; Two heaps pattern. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Heap / Priority Queue strategy.
What critical edge cases must be handled in Find Median from Data Stream?
Essential edge cases to verify include: Single element — median is that single element; Two elements — median is the arithmetic mean of both elements as a floating point double; Incoming stream in already sorted order — two heaps balance correctly without performance degradation; Negative numbers and duplicates — priority queues handle duplicates and negative values natively. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Find Median from Data Stream?
Find Median from Data Stream is a Hard-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Amazon, Microsoft, Google.
Buy me a coffee
Daily Practice
0/0