Find running median from a stream of integers
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
Finding the median in a static set of integers is straightforward: sort the numbers and pick the middle one. However, finding the median of a stream of data, where integers are constantly being added, is more challenging. This is because sorting the data on every addition is inefficient, especially with large streams. The aim is to maintain efficiency while accurately determining the median as each new integer is introduced.
The Median
The median is the middle value in a data set when the numbers are sorted in ascending order. For an odd number of elements, it's simply the central number. For an even number of elements, the median is the average of the two middle numbers.
Solution Overview
To solve the problem of finding the median from a stream of integers efficiently, a common approach is to use two heaps:
- Max Heap: This heap contains the lower half of numbers.
- Min Heap: This heap contains the upper half of numbers.
Key Operations:
- Insertion: Add each incoming integer to one of the heaps.
- Balance: Ensure the heaps are balanced, i.e., their sizes differ by at most one.
- Retrieval: The median is determined based on the sizes of the heaps.
Algorithm
Steps
- Insert an element:
- If the number is less than or equal to the maximum of the max heap, insert it into the max heap.
- Otherwise, insert it into the min heap.
- Balance the heaps:
- If the max heap has more than one extra element compared to the min heap, move the root of the max heap to the min heap.
- If the min heap has more elements than the max heap, move the root of the min heap to the max heap.
- Find the median:
- If both heaps are of equal size, the median is the mean of the root elements of both heaps.
- If one heap has an extra element, the median is the root of that heap.
Example
Consider a stream of integers: 5, 15, 1, 3.
- Insert 5:
Max Heap = [5]
Min Heap = [] - Insert 15:
Max Heap = [5]
Min Heap = [15] - Insert 1:
Max Heap = [1, 5]
Min Heap = [15] - Insert 3:
Max Heap = [1, 3]
Min Heap = [5, 15]
The heaps balance, leading to a median of 4 (the average of 3 and 5).
Complexity
- Time Complexity:
Each insertion and balancing operation isO(log n), wherenis the number of elements. Therefore, the overall time complexity for finding the median in the stream is efficient for real-time processing. - Space Complexity:
Since we are storing all elements in the heaps, the space complexity isO(n).
Pseudocode
Summary
| Step | Description |
| Insert | Add number to appropriate heap based on value |
| Balance | Adjust heaps to ensure size difference is no more than 1 |
| Find Median | If heaps are equal, return mean of roots, else return root of larger heap |
Conclusion
The problem of finding a running median from a stream of numbers is significant in scenarios ranging from financial data analysis to real-time monitoring systems. The described dual-heap solution provides efficient and precise medians, highlighting the power of data structures in computational problems. By understanding and implementing such solutions, developers can effectively manage continuous data streams and derive insightful results seamlessly.
Related reading
- Fixing under replicated partitions in kafka
- Flask + RabbitMQ + SocketIO - forwarding messages
- Flask API as real time kafka consumer
- Flink Kafka connector - commit offset without checkpointing
- Find Second largest number in array at most nlog₂n−2 comparisons
- Find set of numbers in one collection that adds up to a number in another
- Find shortest subarray containing all elements
- Find the 2nd largest element in an array with minimum number of comparisons

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.