Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a number into the max heap.
DSA C++
maxHeap.[1](num); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push to add elements.
Trying to access top instead of inserting.
✗ Incorrect
We use push to add a new element to the heap.
2fill in blank
mediumComplete the code to balance the sizes of the two heaps after insertion.
DSA C++
if (maxHeap.size() > minHeap.size() + [1]) { minHeap.push(maxHeap.top()); maxHeap.pop(); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or 2 instead of 1 for size difference.
Not balancing heaps after insertion.
✗ Incorrect
We balance heaps when maxHeap size is more than minHeap size by 1.
3fill in blank
hardFix the error in the code to get the median when heaps are balanced.
DSA C++
return (maxHeap.top() + [1].top()) / 2.0;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using maxHeap.top() twice.
Using undefined heap names.
✗ Incorrect
The median is average of tops of maxHeap and minHeap, so use minHeap.
4fill in blank
hardFill both blanks to insert a number into the correct heap based on its value.
DSA C++
if (maxHeap.empty() || num [1] maxHeap.top()) { maxHeap.[2](num); } else { minHeap.push(num); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using > instead of < for comparison.
Using pop instead of push to insert.
✗ Incorrect
If number is less than maxHeap top, insert into maxHeap using push.
5fill in blank
hardFill all three blanks to return the median correctly based on heap sizes.
DSA C++
if (maxHeap.size() > minHeap.size()) { return maxHeap.[1](); } else if (minHeap.size() > maxHeap.size()) { return minHeap.[2](); } else { return (maxHeap.top() + minHeap.top()) / [3]; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using size() instead of top() to get element.
Dividing by 2 instead of 2.0 causing integer division.
✗ Incorrect
Return top of the bigger heap or average of both tops divided by 2.0.