Bird
Raised Fist0
DSA Javaprogramming~20 mins

Median of Data Stream Using Two Heaps in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Median Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the median after inserting these numbers?
Given the following sequence of numbers inserted into a Median Finder using two heaps, what is the median after all insertions?

Sequence: 5, 15, 1, 3
DSA Java
MedianFinder mf = new MedianFinder();
mf.addNum(5);
mf.addNum(15);
mf.addNum(1);
mf.addNum(3);
System.out.println(mf.findMedian());
A3.0
B5.0
C6.0
D4.0
Attempts:
2 left
💡 Hint
Remember the median is the middle value or average of two middle values after sorting.
🧠 Conceptual
intermediate
1:30remaining
Why use two heaps to find median in a data stream?
Which reason best explains why two heaps (a max heap and a min heap) are used to find the median in a data stream?
ATo keep the smaller half in max heap and larger half in min heap for quick median calculation
BTo sort all elements in ascending order efficiently
CTo store all elements twice for redundancy
DTo use heaps for faster insertion only, median is found by scanning
Attempts:
2 left
💡 Hint
Think about how median relates to halves of sorted data.
🔧 Debug
advanced
2:00remaining
What error occurs in this MedianFinder code snippet?
Consider this snippet from a MedianFinder class using two heaps. What error will it cause when running?

```java PriorityQueue maxHeap = new PriorityQueue<>(); PriorityQueue minHeap = new PriorityQueue<>(Collections.reverseOrder()); public void addNum(int num) { if (maxHeap.isEmpty() || num <= maxHeap.peek()) { maxHeap.add(num); } else { minHeap.add(num); } } ```
AThe heaps are reversed; maxHeap is min heap and minHeap is max heap causing wrong median
BNullPointerException because heaps are not initialized
CNo error, code runs correctly
DCompilation error due to missing import statements
Attempts:
2 left
💡 Hint
Check how PriorityQueue constructors define heap order.
❓ Predict Output
advanced
2:00remaining
What is the median after these insertions?
Given the following insertions into a MedianFinder, what is the median printed?

Insertions: 2, 4, 7, 1, 5, 3
DSA Java
MedianFinder mf = new MedianFinder();
mf.addNum(2);
mf.addNum(4);
mf.addNum(7);
mf.addNum(1);
mf.addNum(5);
mf.addNum(3);
System.out.println(mf.findMedian());
A4.5
B3.5
C3.0
D4.0
Attempts:
2 left
💡 Hint
Sort the numbers and find the middle two values.
🚀 Application
expert
2:30remaining
How to rebalance heaps after insertion in MedianFinder?
In a MedianFinder using two heaps, after adding a new number, what is the correct way to rebalance the heaps to maintain size property?
AClear both heaps and reinsert all elements sorted
BAlways move the smallest element from min heap to max heap regardless of sizes
CIf one heap has more than one extra element, move the top element from that heap to the other heap
DDo nothing; heaps balance automatically
Attempts:
2 left
💡 Hint
Heaps should differ in size by at most one element.

Practice

(1/5)
1. What is the main purpose of using two heaps (a max heap and a min heap) in the Median of Data Stream problem?
easy
A. To store all numbers in a single data structure
B. To sort all numbers in ascending order
C. To efficiently keep track of the lower half and upper half of the numbers for median calculation
D. To find the maximum number in the data stream

Solution

  1. Step 1: Understand the role of two heaps

    The max heap stores the smaller half of the numbers, and the min heap stores the larger half.
  2. Step 2: Explain median calculation

    By balancing these heaps, the median can be found quickly from the top elements of the heaps.
  3. Final Answer:

    To efficiently keep track of the lower half and upper half of the numbers for median calculation -> Option C
  4. Quick Check:

    Two heaps split data for median [OK]
Hint: Two heaps split data into halves for quick median [OK]
Common Mistakes:
  • Thinking heaps sort all numbers completely
  • Using only one heap for median
  • Confusing max heap and min heap roles
2. Which of the following Java code snippets correctly initializes a max heap using PriorityQueue for the Median of Data Stream problem?
easy
A. PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
B. PriorityQueue<Integer> maxHeap = new PriorityQueue<>();
C. PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.naturalOrder());
D. PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.naturalOrder());

Solution

  1. Step 1: Identify max heap initialization

    Java's PriorityQueue is a min heap by default; to make max heap, use Collections.reverseOrder().
  2. Step 2: Check options

    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); uses Collections.reverseOrder(), which correctly creates a max heap.
  3. Final Answer:

    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); -> Option A
  4. Quick Check:

    Max heap needs reverse order comparator [OK]
Hint: Use Collections.reverseOrder() for max heap in Java [OK]
Common Mistakes:
  • Using default PriorityQueue without comparator
  • Using naturalOrder() which is min heap
  • Using Collections.naturalOrder() which doesn't exist
3. Consider the following Java code snippet for adding numbers to two heaps and finding the median:
MedianFinder mf = new MedianFinder();
mf.addNum(1);
mf.addNum(5);
mf.addNum(2);
System.out.println(mf.findMedian());

Assuming the MedianFinder class uses two heaps correctly, what will be the printed output?
medium
A. 2.5
B. 2
C. 3
D. 1

Solution

  1. Step 1: Add numbers and balance heaps

    Numbers added: 1, 5, 2. Sorted order: 1, 2, 5. Median is middle number 2.
  2. Step 2: Calculate median

    Since odd count, median is the root of the heap with one extra element, which is 2.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    Median of [1,2,5] is 2 [OK]
Hint: Median of odd count is middle element [OK]
Common Mistakes:
  • Calculating average instead of middle for odd count
  • Ignoring heap balancing
  • Confusing median with mean
4. The following Java method is part of a MedianFinder class using two heaps. It is supposed to add a number and rebalance heaps. Identify the bug:
public void addNum(int num) {
    if (maxHeap.isEmpty() || num <= maxHeap.peek()) {
        maxHeap.add(num);
    } else {
        minHeap.add(num);
    }
    if (maxHeap.size() > minHeap.size() + 1) {
        minHeap.add(maxHeap.poll());
    } else if (minHeap.size() > maxHeap.size()) {
        maxHeap.add(minHeap.poll());
    }
}
medium
A. Should check if maxHeap is empty before peek() to avoid NullPointerException
B. The addNum method should not add to minHeap when num equals maxHeap.peek()
C. The rebalance condition for minHeap size is incorrect; should be minHeap.size() > maxHeap.size() + 1
D. No bug, method works correctly

Solution

  1. Step 1: Analyze addNum logic

    It adds to maxHeap if empty or num <= maxHeap.peek(), else to minHeap.
  2. Step 2: Check rebalance conditions

    Rebalances if maxHeap is bigger by more than 1 or minHeap bigger than maxHeap.
  3. Final Answer:

    No bug, method works correctly -> Option D
  4. Quick Check:

    Correct heap balancing logic [OK]
Hint: Check heap sizes differ by at most one [OK]
Common Mistakes:
  • Forgetting to check maxHeap empty before peek
  • Incorrect rebalance size conditions
  • Misplacing elements between heaps
5. You want to extend the MedianFinder class to handle a large data stream efficiently. Which approach improves performance when finding the median after every insertion?
hard
A. Use two balanced heaps to keep halves and rebalance after each insertion
B. Store all numbers in a list and sort it after each insertion
C. Use a single max heap to store all numbers
D. Use a hash map to count frequencies and calculate median from counts

Solution

  1. Step 1: Evaluate approaches for median calculation

    Sorting after each insertion (Store all numbers in a list and sort it after each insertion) is costly (O(n log n)). Single heap or hash map do not support quick median.
  2. Step 2: Explain two heaps efficiency

    Two heaps keep halves balanced, allowing O(log n) insertion and O(1) median retrieval.
  3. Final Answer:

    Use two balanced heaps to keep halves and rebalance after each insertion -> Option A
  4. Quick Check:

    Two heaps optimize median in data stream [OK]
Hint: Two heaps give fast median updates in streams [OK]
Common Mistakes:
  • Sorting entire list each time
  • Using single heap only
  • Ignoring insertion cost
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard