Home/Data Structures & Algorithms/Heaps & Task Schedulers

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Min/max heaps, d-ary heaps, indexed priority queues, running stream medians, and event scheduling.
How to compute Running Median in continuous data streams with O(log N) per tick?
The classic, production-proven design for calculating running medians is the Dual-Heap Balancing Architecture (one Max-Heap and one Min-Heap). 1. The Mental Model Imagine splitting all numbers you've seen so far into two equal halves: The Lower Half (all numbers $le$ median): We store these in a MaxRead more
The classic, production-proven design for calculating running medians is the Dual-Heap Balancing Architecture (one Max-Heap and one Min-Heap).
1. The Mental Model
Imagine splitting all numbers you’ve seen so far into two equal halves:
The median is ALWAYS right at the fingertips: either the top of the Max-Heap, or the average of the two tops!
2. The Two Golden Invariants
To make this work 100% reliably, you must maintain two invariants after every single number is added:
max_heapmust be $le$ every element inmin_heap. (Ifmax_heap.top() > min_heap.top(), swap them).0 <= len(max_heap) - len(min_heap) <= 1.Production Python 3.12 Implementation
Performance & Production Benchmarks
- add_num() Time:
- find_median() Time:
- Space Complexity:
See lessO(log N). Pushing and popping from heaps of sizeN/2takes ~15-20 CPU instructions.O(1). Simply peek at heap roots (index 0). Instantaneous!O(N)total memory to store the incoming stream numbers.