We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
To prevent timeout the algorithm needs to be run in O(logn).
The solution is using two heaps or two priority queues, one max the other min, and always balanced. By balanced, it means the difference of the length of each data structure should be less than or equal to 1. And the min data structure should store the highest half of the sorted list and the max structure needs to store the lowest of the sorted list.
In this way the insersion will take place in O(logn) and finding the median in O(1) as access time to top element of heap or priority queue is O(1).
Heaps: Find the Running Median
You are viewing a single comment's thread. Return to all comments →
To prevent timeout the algorithm needs to be run in O(logn). The solution is using two heaps or two priority queues, one max the other min, and always balanced. By balanced, it means the difference of the length of each data structure should be less than or equal to 1. And the min data structure should store the highest half of the sorted list and the max structure needs to store the lowest of the sorted list. In this way the insersion will take place in O(logn) and finding the median in O(1) as access time to top element of heap or priority queue is O(1).
Here is an implementation in C++: