Challenge - 5 Problems
Median Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat 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
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());
Attempts:
2 left
💡 Hint
Remember the median is the middle value or average of two middle values after sorting.
✗ Incorrect
After inserting 5, 15, 1, 3, the sorted list is [1, 3, 5, 15]. The median is the average of 3 and 5, which is 4.0.
🧠 Conceptual
intermediateWhy 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?
Attempts:
2 left
💡 Hint
Think about how median relates to halves of sorted data.
✗ Incorrect
Two heaps split the data into smaller half (max heap) and larger half (min heap). This allows quick access to median elements without sorting all data.
🔧 Debug
advancedWhat 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);
}
}
```
```java PriorityQueue
Attempts:
2 left
💡 Hint
Check how PriorityQueue constructors define heap order.
✗ Incorrect
maxHeap is created as a min heap (default), and minHeap is created as a max heap (reverse order). This reverses their intended roles causing incorrect median calculation.
❓ Predict Output
advancedWhat 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
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());
Attempts:
2 left
💡 Hint
Sort the numbers and find the middle two values.
✗ Incorrect
Sorted list: [1, 2, 3, 4, 5, 7]. Median is average of 3 and 4 = 3.5.
🚀 Application
expertHow 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?
Attempts:
2 left
💡 Hint
Heaps should differ in size by at most one element.
✗ Incorrect
To keep median calculation correct, heaps must be balanced so their sizes differ by at most one. If imbalance occurs, move the top element from the larger heap to the smaller heap.
