Median-heap
Data Structures
Algorithms
Programming
Computer Science

How to implement a Median-heap

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

The median of a data set is an important statistical measure that divides the set into two equal halves. Calculating the median of a list of numbers can be computationally expensive, especially when the dataset is dynamic and frequently updated. This is where a Median-Heap comes in handy. A Median-Heap is an efficient way to track the median, allowing for quick insertion and median-finding operations.

Understanding the Concept

A Median-Heap is essentially a combination of two heaps:

  • A Max-Heap to track the lower half of numbers.
  • A Min-Heap to track the upper half of numbers.

Together, these heaps allow us to efficiently calculate the median after every insertion in logarithmic time.

Max-Heap and Min-Heap

  • Max-Heap: A binary tree where the value of each node is greater than or equal to the values of its children, with the largest value at the root.
  • Min-Heap: A binary tree where the value of each node is less than or equal to the values of its children, with the smallest value at the root.

Implementation Steps

Below, we will walk through the steps to implement a Median-Heap.

Step 1: Initialize Data Structures

Initialize two heaps: a max-heap and a min-heap. In Python, you can use the `heapq` module, which provides a min-heap by default. To create a max-heap, we can negate the numbers.

  • After inserting `5`: max-heap = `[5]`; min-heap = `[]`.
  • After inserting `3`: max-heap = `[5, 3]`; min-heap = `[]`.
  • After inserting `8`: max-heap = `[5, 3]`; min-heap = `[8]`.
  • After inserting `9`: max-heap = `[5, 3]`; min-heap = `[8, 9]`.
  • Median after each insertion: `5`, `4`, `5`, `6.5`.
  • If elements are inserted in ascending or descending order, the heaps must still be balanced to avoid performance degradation.
  • Handling an empty data set or a single data point.
  • Real-time data stream processing.
  • Dynamic datasets where median calculation is frequently required.
  • Statistical analysis of large datasets.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.