0
0
DSA Javascriptprogramming~30 mins

Median of Data Stream Using Two Heaps in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Median of Data Stream Using Two Heaps
📖 Scenario: Imagine you are building a live dashboard that shows the median value of numbers coming in one by one, like temperatures recorded every minute. You want to keep track of the median efficiently as new numbers arrive.
🎯 Goal: Build a program that uses two heaps (a max heap and a min heap) to find the median of a stream of numbers step-by-step.
📋 What You'll Learn
Create two heaps: a max heap for the smaller half of numbers and a min heap for the larger half.
Add numbers one by one to the correct heap.
Balance the heaps so their sizes differ by at most one.
Calculate the median from the heaps after all numbers are added.
💡 Why This Matters
🌍 Real World
Finding median in real-time data streams like sensor readings, stock prices, or live user inputs.
💼 Career
Useful for roles in data engineering, software development, and analytics where streaming data needs quick summary statistics.
Progress0 / 4 steps
1
Create two empty heaps
Create two empty arrays called maxHeap and minHeap to represent the max heap and min heap respectively.
DSA Javascript
Hint

Use empty arrays to start your heaps.

2
Add a helper function to insert into max heap
Write a function called insertMaxHeap that takes a number and inserts it into maxHeap while keeping it sorted in descending order.
DSA Javascript
Hint

Push the number then sort descending to simulate max heap.

3
Add a helper function to insert into min heap
Write a function called insertMinHeap that takes a number and inserts it into minHeap while keeping it sorted in ascending order.
DSA Javascript
Hint

Push the number then sort ascending to simulate min heap.

4
Add numbers and find median
Write code to add these numbers 5, 15, 1, 3 one by one to the heaps using insertMaxHeap and insertMinHeap. Keep the heaps balanced so their sizes differ by at most one. Then calculate and print the median after all insertions.
DSA Javascript
Hint

Insert each number, balance heaps, then calculate median as middle value or average of two middles.