Spread the word.

Share the link on social media.

Share
  • Facebook
Have an account? Sign In Now

Sign Up Sign Up


Have an account? Sign In Now

Sign In Sign In


Forgot Password?

Don't have account, Sign Up Here

Forgot Password Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

You must login to ask a question.


Forgot Password?

Need An Account, Sign Up Here

You must login to add post.


Forgot Password?

Need An Account, Sign Up Here

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.

RTSALL Logo RTSALL Logo
Sign InSign Up

RTSALL

RTSALL Navigation

  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Tools
    • Run Code
    • JSON Beautifier
    • Regex Tester
    • Diff Checker
    • JWT Decoder
    • UUID Generator
    • .htaccess Generator
    • YAML/JSON Converter
    • SQL Formatter
    • Cron Generator
    • JSON to CSV/Excel
    • System Design Estimator
  • DSA
    • All DSA Problems
    • Online C++ Runner
    • Arrays, Strings & Cache
    • Two Pointers & Sliding Window
    • Linked Lists & Custom Allocators
    • Stacks, Queues & Ring Buffers
    • Trees, BSTs & Indexes
    • Tries & Prefix Search
    • Heaps & Priority Schedulers
    • Hashing & Collision Resolution
    • Graphs & Network Topologies
    • Dynamic Programming
    • Advanced Bitmask & Tree DP
    • Greedy & Resource Allocation
    • Binary Search & State Spaces
    • Bit Manipulation & Low-Level
    • System-Scale & Probabilistic
  • AI Utilities
    • Token Counter
    • JSON Schema Compiler
    • Fine-Tuning JSONL Converter
    • Vector RAG Playground
    • Prompt Optimizer & Architect
    • LLM GPU VRAM Calculator
  • Finance Tools
    • Compound Interest Calculator
    • Simple Interest Calculator
    • Present Value (PV) Calculator
    • Future Value (FV) Calculator
    • NPV Calculator
    • IRR Calculator
    • CAGR Calculator
    • Dividend Income Calculator
    • Yield on Cost Calculator
    • Dividend Payout Ratio
    • WACC Calculator
    • CAPM & Cost of Equity
    • Cost of Debt Calculator
    • DCF Valuation Calculator
    • Enterprise Value Calculator
  • About Us
  • Blog
  • Contact Us
Home/Questions/Q 3525
Next
In Process

RTSALL Latest Articles

abderahman
abderahman
Asked: September 11, 20262026-09-11T09:52:02-05:00 2026-09-11T09:52:02-05:00In: Data Structures & Algorithms, Heaps & Task Schedulers

How to compute Running Median in continuous data streams with O(log N) per tick?

In our telemetry service, financial tick prices arrive at ~10,000 events/second. We need an online algorithm that can output the exact running median at any moment.

Sorting the buffer on every tick is O(N log N), which is impossible at high frequency. What is the standard dual-heap architecture used to maintain running medians in real time?

  • 0
  • 2 2 Answers
  • 0 Followers
  • 0
  • Share
    Share
    • Share on Facebook
    • Share on Twitter
    • Share on LinkedIn
    • Share on WhatsApp

Leave an answer
Cancel reply

You must login to add an answer.


Forgot Password?

Need An Account, Sign Up Here

2 Answers

  • Voted
  • Oldest
  • Recent
  • Random
  1. Abhishek
    Abhishek Begginer
    2026-09-11T21:26:57-05:00Added an answer on September 11, 2026 at 9:26 pm

    Here is the clean C++20 Dual-Heap solution using std::priority_queue with std::greater<int> for the min-heap. This provides O(log N) insertion and O(1) median query.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <queue>
    
    class MedianFinder {
        // Max-heap stores the smaller half of numbers
        std::priority_queue<int> small;
        // Min-heap stores the larger half of numbers
        std::priority_queue<int, std::vector<int>, std::greater<int>> large;
    
    public:
        void addNum(int num) {
            small.push(num);
    
            // Ensure small <= large
            if (!small.empty() && !large.empty() && small.top() > large.top()) {
                large.push(small.top());
                small.pop();
            }
    
            // Maintain size balance (small can have at most 1 more element)
            if (small.size() > large.size() + 1) {
                large.push(small.top());
                small.pop();
            } else if (large.size() > small.size()) {
                small.push(large.top());
                large.pop();
            }
        }
    
        double findMedian() const {
            if (small.size() > large.size()) {
                return static_cast<double>(small.top());
            }
            return (static_cast<double>(small.top()) + large.top()) / 2.0;
        }
    };
    
    int main() {
        MedianFinder mf;
        mf.addNum(5);
        mf.addNum(15);
        std::cout << "Median after [5, 15]: " << mf.findMedian() << "n"; // 10.0
        mf.addNum(1);
        std::cout << "Median after [5, 15, 1]: " << mf.findMedian() << "n"; // 5.0
        mf.addNum(3);
        std::cout << "Median after [5, 15, 1, 3]: " << mf.findMedian() << "n"; // 4.0
        return 0;
    }
    

    Complexity: O(log N) per tick and O(1) for median queries.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  2. Anonymous
    Anonymous Begginer
    2026-09-11T09:52:04-05:00Added an answer on September 11, 2026 at 9:52 am

    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 Max-Heap. Why? Because we only care about the largest number in this half!
    • The Upper Half (all numbers $ge$ median): We store these in a Min-Heap. Why? Because we only care about the smallest number in this half!
       Lower Half (Max-Heap)          Upper Half (Min-Heap)
    [1, 3, 5, 7, 9  -> (TOP: 9)]  <-->  [(TOP: 11) <- 11, 14, 18, 22]
                                         /
                            The Median is 
                         between 9 and 11!
    

    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:

    1. Ordering Invariant: Every element in max_heap must be $le$ every element in min_heap. (If max_heap.top() > min_heap.top(), swap them).
    2. Size Balance Invariant: The size difference between the two heaps must never exceed 1: 0 <= len(max_heap) - len(min_heap) <= 1.

    Production Python 3.12 Implementation

    import heapq
    
    class MedianFinder:
        def __init__(self):
            # Python heapq is a min-heap by default.
            # To simulate a max-heap, multiply values by -1.
            self.small = []  # Max-heap (stores inverted values)
            self.large = []  # Min-heap (stores normal values)
    
        def add_num(self, num: int) -> None:
            # Step 1: Push to max-heap (small half)
            heapq.heappush(self.small, -num)
            
            # Step 2: Ensure ordering invariant (all small <= all large)
            if self.small and self.large and (-self.small[0] > self.large[0]):
                val = -heapq.heappop(self.small)
                heapq.heappush(self.large, val)
                
            # Step 3: Ensure size invariant (len(small) can be at most 1 larger than len(large))
            if len(self.small) > len(self.large) + 1:
                val = -heapq.heappop(self.small)
                heapq.heappush(self.large, val)
            elif len(self.large) > len(self.small):
                val = heapq.heappop(self.large)
                heapq.heappush(self.small, -val)
    
        def find_median(self) -> float:
            if len(self.small) > len(self.large):
                return float(-self.small[0])
            return (-self.small[0] + self.large[0]) / 2.0
    

    Performance & Production Benchmarks

    • add_num() Time: O(log N). Pushing and popping from heaps of size N/2 takes ~15-20 CPU instructions.
    • find_median() Time: O(1). Simply peek at heap roots (index 0). Instantaneous!
    • Space Complexity: O(N) total memory to store the incoming stream numbers.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp

Sidebar

Ask A Question
  • Popular
  • Answers
  • Queryiest

    What is a database?

    • 3 Answers
  • Anonymous

    How to rotate an array in-place with O(1) space and ...

    • 3 Answers
  • hannah

    What steps can businesses take to identify the most valuable ...

    • 2 Answers
  • Vikram
    aarav0 added an answer Direct Technical Solution: Unlike IVFFlat (which partitions vector spaces with… September 11, 2026 at 9:57 pm
  • Abhishek
    Abhishek added an answer Direct Technical Solution: In C++20, range view adaptors (like std::views::filter,… September 11, 2026 at 9:57 pm
  • Sneha Patel
    Anonymous added an answer Direct Technical Solution: torch.cuda.empty_cache() releases only cached (unallocated) blocks back… September 11, 2026 at 9:57 pm

Related Questions

  • pgvector: HNSW index build fails with out-of-memory or high swap: ...

    • 1 Answer
  • Why does std::views::filter on temporary containers trigger undefined behavior and ...

    • 1 Answer
  • PyTorch RuntimeError: CUDA out of memory: Why torch.cuda.empty_cache() fails & ...

    • 1 Answer
  • Next.js 15: Error: Route used "params" without awaiting it (Asynchronous ...

    • 1 Answer
  • Task Scheduler with Cooldowns: Closed-form mathematical formula vs Priority Queue ...

    • 2 Answers

Top Members

Queryiest

Queryiest

  • 201 Questions
  • 295 Points
Enlightened
Anonymous

Anonymous

  • 11 Questions
  • 42 Points
Begginer
paperubofficial

paperubofficial

  • 0 Questions
  • 22 Points
Begginer

Trending Tags

ai asp.net aws basics aws certification aws console aws free tier aws login aws scenario-based questions c++ career cyber security cyber security interview git java javascript jobs jquery net core net core interview questions sql

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • DSA Problems
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • New Questions
  • Trending Questions
  • Must read Questions
  • Hot Questions

Footer

About Us

  • Meet The Team
  • Blog
  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy
  • Disclaimer
  • Terms & Conditions

Help

  • Knowledge Base
  • Support

Follow

© 2023-25 RTSALL. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.