Day 20: Find Median of a Datastream (Two Heaps)

Day 20: Find Median of a Datastream (Two Heaps)

Median of a Datastream

Recommended: Solution

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.

  • For example, for arr = [2,3,4], the median is 3.
  • For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.

Implement the MedianFinder class:

  • MedianFinder() initializes the MedianFinder object.
  • void addNum(int num) adds the integer num from the data stream to the data structure.
  • double findMedian() returns the median of all elements so far. Answers within 10^5 of the actual answer will be accepted.

Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]

Output
[null, null, null, 1.5, null, 2.0]

class MedianFinder:

    def __init__(self):
        # Max-Heap (inverted to use as a max-heap)
        self.low = []
        # Min-Heap
        self.high = []
    
    def addNum(self, num: int) -> None:
        # Add to max-heap (low)
        heapq.heappush(self.low, -num)
        
        # Balance the heaps (ensure every element in low <= every element in high)
        if self.low and self.high and (-self.low[0] > self.high[0]):
            heapq.heappush(self.high, -heapq.heappop(self.low))
        
        # Rebalance sizes
        if len(self.low) > len(self.high) + 1:
            heapq.heappush(self.high, -heapq.heappop(self.low))
        elif len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))
    
    def findMedian(self) -> float:
        # If the number of elements is odd, return the middle element
        if len(self.low) > len(self.high):
            return -self.low[0]
        # If the number of elements is even, return the average of the two middle elements
        return (-self.low[0] + self.high[0]) / 2
        
        

Time Complexity: O(logn)

Space Complexity: O(1)

要查看或添加评论,请登录

Olaoluwa Saola的更多文章

  • Amazon Redshift Data Warehouse Project Using S3, Boto3, and psycopg2

    Amazon Redshift Data Warehouse Project Using S3, Boto3, and psycopg2

    In this project, I worked with Amazon Redshift and S3 to build a data warehouse solution, automating data ingestion and…

    2 条评论
  • Data Warehouse part 2: OLAP vs OLTP

    Data Warehouse part 2: OLAP vs OLTP

    Data engineering plays a pivotal role in modern data management, enabling organizations to efficiently process and…

    2 条评论
  • Building a Data Warehouse Part 1: A Step-by-Step Guide

    Building a Data Warehouse Part 1: A Step-by-Step Guide

    In today’s data-driven world, the ability to effectively store, manage, and analyze large volumes of data is crucial…

    8 条评论
  • Data Engineering 101: Setting Up PostgreSQL with Python

    Data Engineering 101: Setting Up PostgreSQL with Python

    Read article on Medium Data engineering involves managing and processing data for analysis, which often starts with…

    4 条评论
  • Day 19: Modified Binary Search (Search Insert Position)

    Day 19: Modified Binary Search (Search Insert Position)

    Search Insert Position Recommended: Solution Given a sorted array of distinct integers and a target value, return the…

  • Day 18 Missing Number (Cyclic Sort)

    Day 18 Missing Number (Cyclic Sort)

    Missing Number Recommended: Solution Given an array containing distinct numbers in the range , return the only number…

    2 条评论
  • Day 17: Path Sum II (DFS)

    Day 17: Path Sum II (DFS)

    Path Sum II Recommended: Solution Given the of a binary tree and an integer , return all root-to-leaf paths where the…

  • Day 16: Path Sum (Tree Depth First Search)

    Day 16: Path Sum (Tree Depth First Search)

    Path Sum Recommended: Solution Given the of a binary tree and an integer , return if the tree has a root-to-leaf path…

    1 条评论
  • Recap

    Recap

    ?? Here are the links to my previous posts: Day 15: Zig zag Binary Tree Traversal Day 14: Reverse Level order traversal…

    4 条评论
  • Day 15: Zig Zag Binary Tree Traversal (BFS)

    Day 15: Zig Zag Binary Tree Traversal (BFS)

    Zig Zag Binary Tree Traversal Recommended:Solution Time and space complexities : O(n) Leetcode

    2 条评论

社区洞察

其他会员也浏览了