|
| 1 | +LeetCode 295 – Find Median from Data Stream |
| 2 | + |
| 3 | +class MedianFinder { |
| 4 | + private PriorityQueue<Integer> small; // Max Heap |
| 5 | + private PriorityQueue<Integer> large; // Min Heap |
| 6 | + |
| 7 | + public MedianFinder() { |
| 8 | + small = new PriorityQueue<>(Collections.reverseOrder()); |
| 9 | + large = new PriorityQueue<>(); |
| 10 | + } |
| 11 | + |
| 12 | + public void addNum(int num) { |
| 13 | + small.offer(num); |
| 14 | + large.offer(small.poll()); |
| 15 | + |
| 16 | + if (small.size() < large.size()) { |
| 17 | + small.offer(large.poll()); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + public double findMedian() { |
| 22 | + if (small.size() == large.size()) { |
| 23 | + return (small.peek() + large.peek()) / 2.0; |
| 24 | + } |
| 25 | + return small.peek(); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +Explanation |
| 30 | + |
| 31 | +PriorityQueue<Integer> small = MaxHeap (left side) |
| 32 | +PriorityQueue<Integer> large = MinHeap (right side) |
| 33 | +🔹 small: lower half numbers |
| 34 | +🔹 large: upper half numbers |
| 35 | + |
| 36 | +Constructor → dono heaps initialize kiye. |
| 37 | + |
| 38 | +addNum(int num) |
| 39 | +🔹 Step 1: num ko small (maxheap) me daala |
| 40 | +🔹 Step 2: small se top element large (minheap) me daala (to balance) |
| 41 | +🔹 Step 3: Agar large zyada bada ho gaya ho toh wapas small me daal do |
| 42 | + |
| 43 | +→ Is logic se heaps ka balance maintained rahega |
| 44 | + |
| 45 | +findMedian() |
| 46 | +🔹 Agar dono heaps ka size equal hai: |
| 47 | + return average of top elements |
| 48 | +🔹 Agar unequal: |
| 49 | + return top of small (kyunki vo zyada size ka hoga) |
| 50 | + |
| 51 | +Example: |
| 52 | +addNum(1) |
| 53 | +addNum(2) |
| 54 | +findMedian() → 1.5 |
| 55 | + |
| 56 | +addNum(3) |
| 57 | +findMedian() → 2.0 |
| 58 | + |
| 59 | +Time and Space Complexity: |
| 60 | +Operation Time Space |
| 61 | +addNum() O(log n) O(n) |
| 62 | +findMedian() O(1) O(n) |
| 63 | + |
| 64 | +Efficient for dynamic data stream scenarios. |
| 65 | + |
| 66 | +🔗 Need more help or Java tricks? |
| 67 | +https://www.linkedin.com/in/saurabh884095/ |
0 commit comments