Challenge - 5 Problems
Median Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the median after inserting these numbers?
Given a data stream where numbers are inserted one by one, what is the median after inserting the sequence [5, 15, 1, 3] using two heaps (a max heap for the lower half and a min heap for the upper half)?
DSA Typescript
Insert 5 Insert 15 Insert 1 Insert 3 Find median
Attempts:
2 left
💡 Hint
Balance the heaps so their sizes differ by at most one and the max heap contains the smaller half.
✗ Incorrect
After inserting 5, median is 5.
After 15, median is (5+15)/2 = 10.
After 1, median is 5.
After 3, median is (3+5)/2 = 4.
🧠 Conceptual
intermediate1:30remaining
Why use two heaps to find median in a data stream?
What is the main reason for using two heaps (a max heap and a min heap) to find the median in a data stream?
Attempts:
2 left
💡 Hint
Think about how median relates to halves of sorted data.
✗ Incorrect
The two heaps split the data into smaller and larger halves. The max heap stores the smaller half so its root is the largest of the smaller numbers. The min heap stores the larger half so its root is the smallest of the larger numbers. This allows quick median calculation.
🔧 Debug
advanced2:30remaining
Identify the error in this median update code
What error will occur when running this TypeScript code snippet for updating heaps after inserting a new number in the data stream?
DSA Typescript
if (maxHeap.size() === 0 || num > maxHeap.peek()) { minHeap.insert(num); } else { maxHeap.insert(num); } if (maxHeap.size() - minHeap.size() > 1) { minHeap.insert(maxHeap.extract()); } else if (minHeap.size() - maxHeap.size() > 1) { maxHeap.insert(minHeap.extract()); }
Attempts:
2 left
💡 Hint
Consider what happens when maxHeap is empty and peek() is called.
✗ Incorrect
If maxHeap is empty, calling peek() returns undefined or throws an error. Comparing num > undefined causes a runtime error.
❓ Predict Output
advanced2:00remaining
What is the median after these insertions?
Using two heaps, what is the median after inserting the numbers [10, 20, 30, 40, 50] in order?
DSA Typescript
Insert 10 Insert 20 Insert 30 Insert 40 Insert 50 Find median
Attempts:
2 left
💡 Hint
Balance heaps so their sizes differ by at most one and median is root of max heap when odd count.
✗ Incorrect
After inserting all numbers, the median is the middle number 30.
🧠 Conceptual
expert1:30remaining
What is the time complexity of finding median using two heaps?
What is the time complexity for inserting a number and finding the median in a data stream using two heaps?
Attempts:
2 left
💡 Hint
Consider heap insertion and peek operations.
✗ Incorrect
Insertion into a heap takes O(log n) time. Median retrieval is O(1) because it is the root of one or both heaps.