0
0
DSA Goprogramming~3 mins

Why Median of Data Stream Using Two Heaps in DSA Go?

Choose your learning style9 modes available
The Big Idea

What if you could find the middle value instantly, no matter how many numbers you add?

The Scenario

Imagine you are tracking the middle value of a growing list of numbers, like recording daily temperatures. You write down every number and then sort the entire list each time you want to find the middle value.

The Problem

Sorting the whole list every time is slow and tiresome, especially as the list grows longer. It wastes time and can cause mistakes when done manually or with simple code.

The Solution

Using two heaps (one for smaller half, one for larger half) keeps the numbers balanced and lets you quickly find the middle value without sorting everything again and again.

Before vs After
Before
numbers = []
numbers.append(newNumber)
numbers.sort()
median = numbers[len(numbers)//2]
After
smallHeap.Push(newNumber)
// Balance heaps
median = smallHeap.Top()
What It Enables

This method lets you find the median instantly as new numbers come in, making real-time data analysis smooth and fast.

Real Life Example

Streaming apps use this to show live median ratings or prices without delays, even when millions of users add data continuously.

Key Takeaways

Manual sorting each time is slow and inefficient.

Two heaps keep data balanced for quick median access.

Enables fast, real-time median calculation on growing data.