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 3530
Next
In Process

RTSALL Latest Articles

abderahman
abderahman
Asked: September 11, 20262026-09-11T09:52:40-05:00 2026-09-11T09:52:40-05:00In: Data Structures & Algorithms, System-Scale & Probabilistic Structures

How does a Count-Min Sketch estimate heavy-hitter item frequencies under bounded RAM?

We are building a DDoS mitigation filter monitoring billions of network packets per minute. We need to count the frequency of each source IP address in real-time to detect anomalous spikes.

Using a standard hash map of counters would require tens of gigabytes of RAM and quickly run out of memory. We are looking into the Count-Min Sketch algorithm. How does it work mathematically, why does it never underestimate frequency, and how do we choose the optimal table width and depth?

  • 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. Anonymous
    Anonymous Begginer
    2026-09-11T21:26:57-05:00Added an answer on September 11, 2026 at 9:26 pm

    Here is a modern C++ implementation of the Count-Min Sketch for streaming frequency tracking under strict memory caps.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <string>
    #include <cmath>
    #include <algorithm>
    #include <cstdint>
    
    class CountMinSketch {
        int w; // Width (columns)
        int d; // Depth (rows)
        std::vector<std::vector<uint32_t>> table;
    
        uint32_t hash(const std::string& str, int seed) const {
            // FNV-1a 32-bit hash with seed variation
            uint32_t h = 2166136261u ^ seed;
            for (char c : str) {
                h ^= static_cast<uint8_t>(c);
                h *= 16777619u;
            }
            return h % w;
        }
    
    public:
        CountMinSketch(double epsilon = 0.001, double delta = 0.01) {
            w = static_cast<int>(std::ceil(2.71828 / epsilon));
            d = static_cast<int>(std::ceil(std::log(1.0 / delta)));
            table.assign(d, std::vector<uint32_t>(w, 0));
        }
    
        void add(const std::string& item, uint32_t count = 1) {
            for (int r = 0; r < d; ++r) {
                uint32_t col = hash(item, r * 31 + 7);
                table[r][col] += count;
            }
        }
    
        uint32_t query(const std::string& item) const {
            uint32_t min_val = UINT32_MAX;
            for (int r = 0; r < d; ++r) {
                uint32_t col = hash(item, r * 31 + 7);
                min_val = std::min(min_val, table[r][col]);
            }
            return min_val;
        }
    };
    
    int main() {
        CountMinSketch cms(0.01, 0.01);
        cms.add("192.168.1.100", 500);
        cms.add("10.0.0.1", 20);
    
        std::cout << "Estimated frequency 192.168.1.100: " << cms.query("192.168.1.100") << "n";
        std::cout << "Estimated frequency 10.0.0.1:     " << cms.query("10.0.0.1") << "n";
        return 0;
    }
    

    Guarantees: Strictly bounded RAM overhead and zero underestimations.

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

    The Count-Min Sketch (CMS) is the gold-standard probabilistic algorithm for tracking frequencies in massive, unconstrained data streams (used extensively in Apache Spark, network switches, and Google search analytics).

    1. Architectural Layout

    A Count-Min Sketch consists of a 2D matrix of integer counters with d rows (depth) and w columns (width), paired with d independent hash functions:

    Row 0: [0, 0, 0, 0, ..., 0]  <--- Hash Function h_0(x)
    Row 1: [0, 0, 0, 0, ..., 0]  <--- Hash Function h_1(x)
    ...
    Row d: [0, 0, 0, 0, ..., 0]  <--- Hash Function h_d(x)
    

    2. The Operations

    A. Add Item `x` (Increment):

    For each row i from 0 to d - 1, compute column index col = h_i(x) % w, and increment that counter:

    table[i][h_i(x) % w] += 1
    

    B. Query Frequency of `x` (Point Query):

    Because multiple items might collide at the same counter bucket, hash collisions can only increase a counter, never decrease it!

    Therefore, to get the best possible estimate, we take the MINIMUM across all d rows:

    estimated_count = min(table[i][h_i(x) % w] for i in range(d))
    

    The Golden Invariant: A Count-Min Sketch NEVER underestimates the true count! True frequency is always $le$ estimated frequency.


    3. Mathematical Dimensioning Rules

    If you want an error bound within $epsilon cdot N$ with confidence probability $1 – delta$:

    • Width: $w = lceil rac{e}{epsilon}
      ceil pprox lceil rac{2.718}{epsilon}
      ceil$
    • Depth: $d = lceil ln( rac{1}{delta})
      ceil$

    For example, to guarantee $le 0.1%$ error with $99%$ confidence, you need only $w = 2718$ columns and $d = 5$ rows. That’s just 13,590 integer counters (~54 KB of RAM) to monitor billions of events!


    Clean Python 3.12 Implementation

    import math
    import mmh3 # MurmurHash3
    
    class CountMinSketch:
        def __init__(self, epsilon: float = 0.001, delta: float = 0.01):
            self.w = int(math.ceil(math.e / epsilon))
            self.d = int(math.ceil(math.log(1.0 / delta)))
            self.table = [[0] * self.w for _ in range(self.d)]
    
        def add(self, item: str, count: int = 1) -> None:
            """Increments counter for item across all d hash functions."""
            for row in range(self.d):
                col = mmh3.hash(item, row, signed=False) % self.w
                self.table[row][col] += count
    
        def query(self, item: str) -> int:
            """Returns minimum count across all d rows (never underestimates)."""
            return min(
                self.table[row][mmh3.hash(item, row, signed=False) % self.w]
                for row in range(self.d)
            )
    

    Complexity Breakdown

    • Add Time: O(d) — strictly constant time ($5$ hash calculations and memory writes).
    • Query Time: O(d) — strictly constant time ($5$ lookups).
    • Memory Footprint: O(w * d) — strictly fixed in size. Bounded memory that never grows regardless of how many billions of packets arrive!
    • 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.