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.
arr = [2,3,4], the median is 3.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 <= 105findMedian.5 * 104 calls will be made to addNum and findMedian.Follow up:
[0, 100], how would you optimize your solution?99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?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:
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:
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.0To 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:
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| Case | How to Handle |
|---|---|
| Median request when zero numbers have been added to the data stream | 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 | 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 | 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 | 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 | 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 | 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 | 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 | Using two logarithmic time heaps ensures that both insertion and median retrieval remain efficient at scale. |