|
| 1 | +package com.thealgorithms.datastructures.heaps; |
| 2 | + |
| 3 | +import java.util.PriorityQueue; |
| 4 | + |
| 5 | +/** |
| 6 | + * This class maintains the median of a dynamically changing data stream using |
| 7 | + * two heaps: a max-heap and a min-heap. The max-heap stores the smaller half |
| 8 | + * of the numbers, and the min-heap stores the larger half. |
| 9 | + * This data structure ensures that retrieving the median is efficient. |
| 10 | + * |
| 11 | + * Time Complexity: |
| 12 | + * - Adding a number: O(log n) due to heap insertion. |
| 13 | + * - Finding the median: O(1). |
| 14 | + * |
| 15 | + * Space Complexity: O(n), where n is the total number of elements added. |
| 16 | + * |
| 17 | + * @author Hardvan |
| 18 | + */ |
| 19 | +public final class MedianFinder { |
| 20 | + MedianFinder() { |
| 21 | + } |
| 22 | + |
| 23 | + private PriorityQueue<Integer> minHeap = new PriorityQueue<>(); |
| 24 | + private PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a); |
| 25 | + |
| 26 | + /** |
| 27 | + * Adds a new number to the data stream. The number is placed in the appropriate |
| 28 | + * heap to maintain the balance between the two heaps. |
| 29 | + * |
| 30 | + * @param num the number to be added to the data stream |
| 31 | + */ |
| 32 | + public void addNum(int num) { |
| 33 | + if (maxHeap.isEmpty() || num <= maxHeap.peek()) { |
| 34 | + maxHeap.offer(num); |
| 35 | + } else { |
| 36 | + minHeap.offer(num); |
| 37 | + } |
| 38 | + |
| 39 | + if (maxHeap.size() > minHeap.size() + 1) { |
| 40 | + minHeap.offer(maxHeap.poll()); |
| 41 | + } else if (minHeap.size() > maxHeap.size()) { |
| 42 | + maxHeap.offer(minHeap.poll()); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Finds the median of the numbers added so far. If the total number of elements |
| 48 | + * is even, the median is the average of the two middle elements. If odd, the |
| 49 | + * median is the middle element from the max-heap. |
| 50 | + * |
| 51 | + * @return the median of the numbers in the data stream |
| 52 | + */ |
| 53 | + public double findMedian() { |
| 54 | + if (maxHeap.size() == minHeap.size()) { |
| 55 | + return (maxHeap.peek() + minHeap.peek()) / 2.0; |
| 56 | + } |
| 57 | + return maxHeap.peek(); |
| 58 | + } |
| 59 | +} |
0 commit comments