AlgoMaster Logo

Find Median from Data Stream

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

In the brute force approach, every time we add a new number to our data structure, we will insert it into an existing list and sort it. This will allow us to easily compute the median by accessing the middle element(s) of the sorted list.

Approach:

  1. Use a dynamic array to store the numbers.
  2. addNum(int num): Insert the incoming number into this array and then sort it.
  3. findMedian(): Access the middle element or the average of two middle elements to get the median.

Code:

2. Two Heaps Approach

Intuition:

To optimize the process, we can use two heaps:

  • A max heap for the left part
  • A min heap for the right part

The median can be quickly found by:

  • Taking the top of one or both heaps, depending on the number of elements.

Approach:

  1. Maintain two heaps:
    • A max heap to store the smaller half of the numbers.
    • A min heap to store the larger half of the numbers.
  2. addNum(int num):
    • If the new number is less than the max in max heap, add to max heap; otherwise, add to the min heap.
    • Balance the heaps so they contain equal numbers, or max heap has one extra.
  3. findMedian():
    • If both heaps have the same size, the median is the average of the tops of both heaps.
    • If max heap has one more element, the median is its top.

Code: