0
0
DSA Typescriptprogramming~20 mins

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

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Median Mastery
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 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
A6
B4
C5
D3
Attempts:
2 left
💡 Hint
Balance the heaps so their sizes differ by at most one and the max heap contains the smaller half.
🧠 Conceptual
intermediate
1: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?
ATo store all elements twice for redundancy
BTo sort all elements in ascending order efficiently
CTo keep the smaller half in max heap and larger half in min heap for quick median access
DTo use heaps as queues for faster insertion
Attempts:
2 left
💡 Hint
Think about how median relates to halves of sorted data.
🔧 Debug
advanced
2: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());
}
ARuntime error because maxHeap.peek() may be undefined when maxHeap is empty
BNo error, code runs correctly
CLogical error: heaps are never balanced
DSyntax error due to missing semicolon
Attempts:
2 left
💡 Hint
Consider what happens when maxHeap is empty and peek() is called.
Predict Output
advanced
2: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
A35
B25
C20
D30
Attempts:
2 left
💡 Hint
Balance heaps so their sizes differ by at most one and median is root of max heap when odd count.
🧠 Conceptual
expert
1: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?
AInsertion: O(log n), Median retrieval: O(1)
BInsertion: O(n), Median retrieval: O(log n)
CInsertion: O(1), Median retrieval: O(n)
DInsertion: O(n log n), Median retrieval: O(1)
Attempts:
2 left
💡 Hint
Consider heap insertion and peek operations.