Taro Logo

Find Median from Data Stream

#20 Most AskedHard
0 views
Topics:
ArraysTwo Pointers

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.

Example 1:

Input
["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output
[null, null, null, 1.5, null, 2.0]

Explanation
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)
medianFinder.addNum(3);    // arr[1, 2, 3]
medianFinder.findMedian(); // return 2.0

Constraints:

  • -105 <= num <= 105
  • There will be at least one element in the data structure before calling findMedian.
  • At most 5 * 104 calls will be made to addNum and findMedian.

Follow up:

  • If all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?
  • If 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected return type for the median? Should it be a floating-point number (e.g., `double`) to handle cases with an even number of elements, or can it be an integer if the median falls directly on an element?
  2. Are duplicate numbers allowed in the data stream, and if so, how should they be factored into the median calculation?
  3. What is the maximum number of elements we can expect to receive in the data stream over time, or approximately how many `addNum` operations will be called?
  4. Can I assume that `findMedian` will only be called after at least one number has been added to the data structure, or do I need to handle the edge case of an empty data stream?
  5. What is the expected range of the integer values coming from the data stream (e.g., standard 32-bit integers, or could they be outside standard bounds)?

Brute Force Solution

Approach

Imagine you are running a scoreboard where numbers arrive one by one, and someone constantly asks you for the exact middle value of all the numbers received so far. The brute force approach involves keeping every single number you have ever received in a single list and completely reorganizing that list into numerical order every time a new number arrives.

Here's how the algorithm would work step-by-step:

  1. Keep a running collection of all the numbers that have been given to you so far.
  2. Whenever a new number arrives, simply add it to the end of your collection.
  3. To find the middle value, gather all the numbers currently in your collection and line them up strictly from smallest to largest.
  4. Count how many total numbers you have in your ordered line.
  5. If the total count is an odd number, look directly at the single number sitting right in the exact center of the line and declare that as your answer.
  6. If the total count is an even number, find the two numbers sitting right next to each other in the exact center, add them together, and split that total in half to get your answer.
  7. Repeat this entire sorting and counting process every single time a new number is added to your collection.

Code Implementation

class MedianFinder:
    def __init__(self):
        # Initialize an empty list to store all incoming numbers chronologically
        self.number_collection = []

    def addNum(self, incoming_number: int) -> None:
        self.number_collection.append(incoming_number)

    def findMedian(self) -> float:
        # Sort the entire collection on demand to keep elements in numerical order
        sorted_collection = sorted(self.number_collection)
        total_count = len(sorted_collection)
        center_index = total_count // 2

        # Branch based on parity because median calculation differs for odd and even counts
        if total_count % 2 != 0:
            return float(sorted_collection[center_index])
        else:
            left_center = sorted_collection[center_index - 1]
            right_center = sorted_collection[center_index]
            return (left_center + right_center) / 2.0

Big(O) Analysis

Time Complexity
O(n²) – For each of the n numbers that arrive from the data stream, we add the element to our collection and then sort the entire list from scratch. Sorting a collection of size n takes proportional to n log n time, but we must do this after every single one of the n insertions. This repeated sorting drives the cost, leading to approximately n * n operations total. Simplifying this overall work results in an overall time complexity of O(n²).
Space Complexity
O(N) – To implement the running collection described in the steps, we utilize an auxiliary list that grows dynamically as each new number arrives. Letting N represent the total number of elements added to the stream so far, this list stores every single input value sequentially. Consequently, the auxiliary memory scales in direct proportion to the number of incoming elements, leading to a linear space complexity of O(N).

Optimal Solution

Approach

To find the middle value of a constantly growing line of numbers, we can divide the group into two equal halves using a clever balancing trick. By keeping the smaller numbers in one group and the larger numbers in another, we can instantly peek at the boundary values to find the middle without ever needing to sort the whole collection.

Here's how the algorithm would work step-by-step:

  1. Imagine splitting the incoming numbers into two distinct piles: a lower pile and an upper pile.
  2. Arrange the lower pile so that its largest number sits right at the top, ready for us to see.
  3. Arrange the upper pile so that its smallest number sits right at the top, also ready for us to see.
  4. Whenever a new number arrives, compare it to the current boundaries and drop it into the appropriate pile.
  5. After placing the new number, check the sizes of both piles to make sure they remain balanced so that neither pile has more than one extra number compared to the other.
  6. If one pile ever becomes too heavy, take its top number and slide it over to the other pile to restore balance.
  7. When someone asks for the middle value, simply look at the top numbers of the piles.
  8. If both piles contain the same amount of numbers, calculate the middle ground between the two top numbers.
  9. If one pile has more numbers than the other, the middle value is simply the top number of that larger pile.

Code Implementation

import heapq

class MedianFinder:
    def __init__(self):
        self.lower_half_max_heap = []
        self.upper_half_min_heap = []

    def addNum(self, incoming_number: int) -> None:
        # We invert values for the lower pile to simulate a max-heap using Python min-heap.
        heapq.heappush(self.lower_half_max_heap, -incoming_number)
        
        balancing_value = -heapq.heappop(self.lower_half_max_heap)
        heapq.heappush(self.upper_half_min_heap, balancing_value)

        # Ensure the lower pile always has equal size or at most one extra element.
        if len(self.upper_half_min_heap) > len(self.lower_half_max_heap):
            shifted_value = heapq.heappop(self.upper_half_min_heap)
            heapq.heappush(self.lower_half_max_heap, -shifted_value)

    def findMedian(self) -> float:
        # When piles are balanced, the median is the average of both inner boundaries.
        if len(self.lower_half_max_heap) > len(self.upper_half_min_heap):
            return -self.lower_half_max_heap[0]
        
        return (-self.lower_half_max_heap[0] + self.upper_half_min_heap[0]) / 2.0

Big(O) Analysis

Time Complexity
O(log n) – For each of the n incoming numbers, we insert the element into one of the two heaps, which takes logarithmic time proportional to the heap size. Balancing the piles involves at most a constant number of heap insertions and extractions, each also taking O(log n) time. Finding the median requires only constant time O(1) by peeking at the root elements. Across all n operations, the total cost approximates n * log n, which simplifies to O(log n) per insertion and O(1) for finding the median.
Space Complexity
O(n) – The auxiliary space is driven by the two heap data structures described in the steps as the lower pile and the upper pile. As N numbers are added to the data stream, every single number is eventually stored across these two heaps, consuming memory proportional to the total number of elements. Therefore, the total extra memory grows linearly with the input size N, resulting in O(n) auxiliary space complexity.

Edge Cases

Median request when zero numbers have been added to the data stream
How to Handle:
Return a default value or throw a clear exception since no median is mathematically defined for an empty set.
Data stream containing only one single element
How to Handle:
Both heaps will be empty except for the max heap holding that single element, which is directly returned as the median.
Data stream containing an even number of total elements
How to Handle:
Compute the median by taking the average of the maximum element from the left max heap and the minimum element from the right min heap.
Data stream containing an odd number of total elements
How to Handle:
Design the heap balancing logic so the extra element always resides in the max heap, allowing us to return its top as the median instantly.
Stream containing all identical values
How to Handle:
Heaps will handle duplicate values correctly by balancing counts, and the median calculation will accurately return that repeated value.
Stream containing negative numbers, zeros, and positive numbers mixed together
How to Handle:
Standard heap comparisons work independently of sign, allowing negative and positive numbers to partition correctly across both heaps.
Extremely large volume of incoming numbers causing integer overflow when computing the median of two large integers
How to Handle:
Cast the sum of the two middle elements to a floating-point data type before dividing by two to prevent overflow and precision loss.
Massive data stream with millions of insertions requiring high throughput
How to Handle:
Using two logarithmic time heaps ensures that both insertion and median retrieval remain efficient at scale.
0/45 completed