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!
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.
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.
To efficiently calculate the median from a data stream, we use two essential data structures:
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.
Let's dive into the code and see how we can implement a solution to find the median from a data stream using 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.5What 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! š