Find Median from Data Stream šŸŽÆ

beginner
24 min

Find Median from Data Stream šŸŽÆ

Welcome to another exciting lesson at CodeYourCraft! Today, we'll delve into the fascinating world of Data Structures and Algorithms, focusing on finding the median from a data stream. Let's get started!

What is the Median? šŸ“

The median is the middle value in a sorted list of numbers. If the list has an odd number of observations, the middle value is the median. If the list has an even number of observations, the median is the average of the two middle values.

Why Find the Median from a Data Stream? šŸ’”

In real-world scenarios, data streams are continuous and vast. Finding the median from a data stream helps us understand the central tendency of the data and make informed decisions. For example, in finance, the median income can give us a better understanding of income distribution compared to the mean.

Data Structures for Median Calculation šŸ“

To efficiently calculate the median from a data stream, we use two essential data structures:

  1. Heap (Max Heap or Min Heap)
  2. Priority Queue

Max Heap vs Min Heap šŸ’”

A Max Heap is a complete binary tree where each parent node is greater than or equal to its child nodes. A Min Heap is the opposite, where each parent node is smaller than or equal to its child nodes.

Implementing Median from Data Stream šŸŽÆ

Let's dive into the code and see how we can implement a solution to find the median from a data stream using Python:

python
class MedianFinder: def __init__(self): self.min_heap = [] self.max_heap = [] def addNum(self, num: int) -> None: """ Inserts a number into the data structure. """ if not self.min_heap: self.min_heap.append(num) self.update_max_heap() else: if num < self.min_heap[0]: self.min_heap.append(num) self.update_max_heap() else: heappush(self.max_heap, -num) if len(self.max_heap) > len(self.min_heap) + 1: self.min_heap.append(-heappop(self.max_heap)) self.update_max_heap() def findMedian(self) -> float: """ Returns the median of current data stream. """ if len(self.min_heap) > len(self.max_heap): return self.min_heap[len(self.min_heap) // 2] else: return (self.min_heap[len(self.min_heap) // 2] - self.max_heap[0]) / 2 def update_max_heap(self): """ Maintains the max heap invariant after inserting a number. """ if self.max_heap and self.max_heap[0] < -self.min_heap[0]: heappush(self.max_heap, -heappop(self.min_heap)) self.update_max_heap() # Example usage medianFinder = MedianFinder() medianFinder.addNum(1) medianFinder.addNum(2) print(medianFinder.findMedian()) # Output: 1.5

Practice Time! šŸŽÆ

Quick Quiz
Question 1 of 1

What is the median of the list [3, 5, 1, 4]?

We hope you enjoyed learning about finding the median from a data stream! Keep practicing, and you'll be a master in no time. Happy coding! šŸš€