Skip to content

Find Median from Data Stream

LeetCode #295 - Find Median from Data Stream

Section titled “LeetCode #295 - Find Median from Data Stream”

Solve this classic coding interview problem efficiently using multiple approaches.

InputOutputExplanation
[example1]result1Explanation goes here
[example2]result2Explanation goes here
  • Standard LeetCode constraints
  • Refer to the official problem statement for exact details
ApproachAdd/Find MedianSpaceBest When
Two HeapsO(log n) / O(1)O(n)Optimal for streaming
Balanced BSTO(log n) / O(log n)O(n)Self-balancing trees
Sorted ListO(n) / O(1)O(n)Simpler implementation
  • Pick Two Heaps for the optimal streaming solution.
  • Pick Balanced BST for a theoretical balanced approach.
  • Pick Sorted List if you are learning from scratch.
Optimal
Two Heaps
O(log n) add · O(1) median
Balanced Tree
Balanced BST
O(log n) add · O(log n) median
Simple
Sorted List
O(n) add · O(1) median
★ Recommended

Maintain two heaps: a max heap for the smaller half and a min heap for the larger half. Keep them balanced so the median is either the root of one or the average of both roots.

⏱ Time O(log n) Add/Find 💾 Space O(n) Heap storage
find_median_from_data_stream_two_heaps.py
from typing import List
def find_median_from_data_stream_two_heaps(nums: List[int]) -> int:
"""
Find Median From Data Stream - Two Heaps approach.
Time: O(n), Space: O(1) or O(n) depending on approach
"""
pass
if __name__ == "__main__":
# Test cases
pass
🎯 Interview Favourite

Use a self-balancing binary search tree to maintain sorted order and compute the median dynamically.

⏱ Time O(log n) Balanced tree ops 💾 Space O(n) Tree storage
find_median_from_data_stream_balanced_bst.py
from typing import List
def find_median_from_data_stream_balanced_bst(nums: List[int]) -> int:
"""
Find Median From Data Stream - Balanced Bst approach.
Time: O(n), Space: O(1) or O(n) depending on approach
"""
pass
if __name__ == "__main__":
# Test cases
pass
✓ Simple

Maintain a sorted list and insert each new number in the correct position. The median is found at the middle position.

⏱ Time O(n) Linear insertion 💾 Space O(n) List storage
find_median_from_data_stream_sorted_list.py
from typing import List
def find_median_from_data_stream_sorted_list(nums: List[int]) -> int:
"""
Find Median From Data Stream - Sorted List approach.
Time: O(n), Space: O(1) or O(n) depending on approach
"""
pass
if __name__ == "__main__":
# Test cases
pass