Bird
Raised Fist0
DSA Goprogramming~10 mins

Median of Data Stream Using Two Heaps in DSA Go - Interactive Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the max heap for the lower half of numbers.

DSA Go
maxHeap := &IntHeap[1]
Drag options to blanks, or click blank then click option'
A[]int{}
B{}
Cmake([]int, 0)
Dnil
Attempts:
3 left
💡 Hint
Common Mistakes
Using nil instead of an empty slice causes runtime errors when pushing.
Using {} is invalid syntax for slice initialization.
2fill in blank
medium

Complete the code to push a number into the max heap.

DSA Go
heap.[1](maxHeap, num)
Drag options to blanks, or click blank then click option'
AInsert
Bpush
CAdd
DPush
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'push' causes compilation errors.
Using 'Add' or 'Insert' are not valid heap package methods.
3fill in blank
hard

Fix the error in the code to pop the smallest number from the min heap.

DSA Go
smallest := heap.[1](minHeap).(int)
Drag options to blanks, or click blank then click option'
Apop
BRemove
CPop
DExtract
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'pop' causes compilation errors.
Using 'Remove' or 'Extract' are not valid heap package methods.
4fill in blank
hard

Fill both blanks to balance the heaps by moving the top element from maxHeap to minHeap.

DSA Go
top := heap.[1](maxHeap).(int)
heap.[2](minHeap, top)
Drag options to blanks, or click blank then click option'
APop
BPush
CRemove
DInsert
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Remove' or 'Insert' instead of 'Pop' and 'Push'.
Mixing up the order of operations.
5fill in blank
hard

Fill all three blanks to calculate the median from the two heaps.

DSA Go
if maxHeap.Len() > minHeap.Len() {
    median := float64(maxHeap.[1]().(int))
    return median
} else {
    median := (float64(maxHeap.[2]().(int)) + float64(minHeap.[3]().(int))) / 2
    return median
}
Drag options to blanks, or click blank then click option'
APeek
BPop
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Pop' removes elements and changes the heaps incorrectly.
Not accessing the top elements properly.

Practice

(1/5)
1. What is the main purpose of using two heaps (a max-heap and a min-heap) in finding the median of a data stream?
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 separately
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 how this helps find the median

    By balancing these heaps, the median is either the top of one heap or the average of the tops of both heaps.
  3. Final Answer:

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

    Two heaps split data halves = A [OK]
Hint: Two heaps split data halves for median [OK]
Common Mistakes:
  • Thinking heaps sort all numbers fully
  • Using one heap only
  • Confusing max-heap and min-heap roles
2. Which of the following Go code snippets correctly initializes a max-heap and a min-heap for integers using container/heap package?
easy
A. maxHeap := &IntMaxHeap{}; minHeap := &IntMinHeap{}
B. maxHeap := heap.New(IntMaxHeap{}); minHeap := heap.New(IntMinHeap{})
C. maxHeap := &IntMinHeap{}; minHeap := &IntMaxHeap{}
D. maxHeap := make([]int, 0); minHeap := make([]int, 0)

Solution

  1. Step 1: Recognize heap initialization in Go

    Heaps are initialized as pointers to custom heap types that implement heap.Interface.
  2. Step 2: Identify correct syntax

    Using &IntMaxHeap{} and &IntMinHeap{} creates pointers to heap structs ready for heap operations.
  3. Final Answer:

    maxHeap := &IntMaxHeap{}; minHeap := &IntMinHeap{} -> Option A
  4. Quick Check:

    Pointer to heap struct = A [OK]
Hint: Use pointers to heap structs for container/heap [OK]
Common Mistakes:
  • Using heap.New which does not exist
  • Swapping max-heap and min-heap types
  • Initializing as slices without heap.Interface
3. Given the following sequence of numbers inserted into the data stream: 5, 15, 1, 3, what is the median after all insertions using two heaps?
medium
A. 5
B. 8
C. 3
D. 4

Solution

  1. Step 1: Insert numbers and balance heaps

    Insert 5 (maxHeap top=5); insert 15 (minHeap top=15); insert 1 ≤5 (maxHeap top=5, contains 5,1); insert 3 ≤5 (maxHeap top=5, contains 5,1,3), balance: len=3 >1+1, pop 5 -> push minHeap top=5 (15,5), maxHeap top=3 (1,3).
  2. Step 2: Calculate median from heaps

    Heaps sizes equal (2 each). Median = average of maxHeap top (3) and minHeap top (5) = (3+5)/2 = 4.
  3. Final Answer:

    4 -> Option D
  4. Quick Check:

    Median = (3+5)/2 = 4 [OK]
Hint: Median is average of two heap tops if sizes equal [OK]
Common Mistakes:
  • Taking median as maxHeap top only
  • Not balancing heaps after insertion
  • Calculating median as sum instead of average
4. In the following Go code snippet for median calculation, what is the bug?
func addNum(num int) {
  if maxHeap.Len() == 0 || num <= (*maxHeap)[0] {
    heap.Push(maxHeap, num)
  } else {
    heap.Push(minHeap, num)
  }
  if maxHeap.Len() > minHeap.Len()+1 {
    heap.Push(minHeap, heap.Pop(maxHeap))
  } else if minHeap.Len() > maxHeap.Len() {
    heap.Push(maxHeap, heap.Pop(minHeap))
  }
}
medium
A. Heaps are not balanced after insertion
B. Comparison operator should be < instead of <=
C. heap.Pop returns interface{}, needs type assertion before Push
D. maxHeap and minHeap are swapped in conditions

Solution

  1. Step 1: Analyze balancing logic

    The first condition correctly balances when maxHeap is too large (> minHeap.Len()+1). But the second condition checks minHeap.Len() > maxHeap.Len(), which triggers rebalance correctly when minHeap is larger.
  2. Step 2: Why heaps are not balanced

    Original code used > maxHeap.Len() + 1 which fails to rebalance when minHeap is exactly one larger. Changing to > maxHeap.Len() fixes this.
  3. Final Answer:

    Heaps are not balanced after insertion -> Option A
  4. Quick Check:

    minHeap balance: > max.Len() [OK]
Hint: minHeap balance when len(min) > len(max) [OK]
Common Mistakes:
  • Using +1 symmetrically for both balance conditions
  • Wrong size difference in minHeap check
  • Not balancing after every insertion
5. You want to find the median of a large data stream where numbers can be negative, zero, or positive. Which approach using two heaps ensures correct median calculation even with duplicates and negative values?
hard
A. Use a single max-heap and pop elements until median is found
B. Use a max-heap for lower half and min-heap for upper half, balance sizes, and calculate median from tops
C. Sort all numbers in an array and pick middle element(s) each time
D. Use two min-heaps and merge their outputs to find median

Solution

  1. Step 1: Choose correct heap types for halves

    Max-heap stores lower half (including negatives), min-heap stores upper half, handling all values correctly.
  2. Step 2: Balance heaps and compute median

    Keep heaps balanced in size; median is top of max-heap if odd count, or average of tops if even count.
  3. Final Answer:

    Use a max-heap for lower half and min-heap for upper half, balance sizes, and calculate median from tops -> Option B
  4. Quick Check:

    Two heaps balanced handle negatives and duplicates [OK]
Hint: Balance max and min heaps for all number ranges [OK]
Common Mistakes:
  • Using two min-heaps which can't split halves properly
  • Sorting entire stream each time (inefficient)
  • Using single heap only
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