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

System-Scale & Probabilistic Structures

LSM-trees, HyperLogLog, Count-Min sketches, Roaring Bitmaps, Fenwick trees, Segment trees, and HNSW graphs.

Share
  • Facebook
0 Followers
5 Answers
3 Questions
Home/Data Structures & Algorithms/System-Scale & Probabilistic Structures
  • Recent Questions
  • Most Answered
  • Answers
  • No Answers
  • Most Visited
  • Most Voted
  • Random
  1. Asked: September 11, 2026In: System-Scale & Probabilistic Structures

    pgvector: HNSW index build fails with out-of-memory or high swap: How to tune maintenance_work_mem & parallel workers

    aarav0
    aarav0
    Added an answer on September 11, 2026 at 9:57 pm

    Direct Technical Solution: Unlike IVFFlat (which partitions vector spaces with k-means centroids), HNSW (Hierarchical Navigable Small World) constructs a multi-layer proximity graph in physical RAM during build time. For 2,000,000 vectors with 1,536 dimensions, the raw vectors alone occupy 2,000,000Read more

    Direct Technical Solution: Unlike IVFFlat (which partitions vector spaces with k-means centroids), HNSW (Hierarchical Navigable Small World) constructs a multi-layer proximity graph in physical RAM during build time. For 2,000,000 vectors with 1,536 dimensions, the raw vectors alone occupy 2,000,000 × 1,536 × 4 bytes = 12.28 GB. Adding the HNSW graph neighbor connectivity lists (with m=16) increases total build RAM requirement to approximately 18 to 22 GB.

    1. The Formula to Calculate Required `maintenance_work_mem`

    Required RAM (Bytes) ≈ Rows × ((dimensions × 4) + (8 × M)) × 1.2 (Index Graph Overhead)

    2. PostgreSQL Configuration Tuning

    Temporarily allocate sufficient RAM to the session before triggering the index build, and utilize parallel CPU worker cores to accelerate graph edge exploration:

    -- Execute inside the active database session before CREATE INDEX:
    SET maintenance_work_mem = '24GB';
    SET max_parallel_maintenance_workers = 4;
    SET max_parallel_workers = 8;
    
    -- Now trigger the HNSW index build
    CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_documents_hnsw
    ON documents USING hnsw (embedding vector_cosine_ops) 
    WITH (m = 16, ef_construction = 64);
    
    -- Reset back to default after build completes
    RESET maintenance_work_mem;

    3. When to Use IVFFlat vs HNSW

    MetricHNSW IndexIVFFlat Index
    Build RAM RequirementHigh (18–24 GB for 2M vectors)Low (2–4 GB)
    Query Latency (QPS)Sub-5ms (Blazing fast graph traversal)15–50ms (Linear list scan)
    Recall Accuracy98%+ true nearest neighbors85–92% (Approximate centroid scan)
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  2. Asked: September 11, 2026In: Data Structures & Algorithms, System-Scale & Probabilistic Structures

    How does a Fenwick Tree (Binary Indexed Tree) query and update prefix sums in O(log N) using i & (-i)?

    Abhay Tiwari
    Abhay Tiwari Begginer
    Added an answer on September 11, 2026 at 9:53 am

    The Fenwick Tree (invented by Peter Fenwick in 1994) is one of the most compact data structures ever devised. It gives you the full power of a dynamic segment tree in just one flat array of size N with 10 lines of code. 1. The Secret: Powers of 2 Range Decomposition Any positive integer can be uniquRead more

    The Fenwick Tree (invented by Peter Fenwick in 1994) is one of the most compact data structures ever devised. It gives you the full power of a dynamic segment tree in just one flat array of size N with 10 lines of code.

    1. The Secret: Powers of 2 Range Decomposition

    Any positive integer can be uniquely represented as a sum of powers of 2. For example: 13 = 8 + 4 + 1.

    Fenwick took this idea and applied it to prefix ranges: instead of storing every single element, tree[i] stores the sum of a contiguous range of length equal to its lowest set bit!

    The length of the range responsible by index i is given by: lowbit(i) = i & (-i).

    • If i = 12 (1100_2): lowbit(12) = 4. So tree[12] stores the sum of 4 elements: indices [9, 10, 11, 12]!
    • If i = 8 (1000_2): lowbit(8) = 8. So tree[8] stores the sum of the first 8 elements: [1 ... 8]!

    2. The Two Operations

    A. Prefix Sum Query: `i -= (i & -i)`

    To calculate the prefix sum up to index 13:

    1. Read tree[13] (covers index 13). 13 - lowbit(13) = 13 - 1 = 12.
    2. Read tree[12] (covers indices 9 through 12). 12 - lowbit(12) = 12 - 4 = 8.
    3. Read tree[8] (covers indices 1 through 8). 8 - lowbit(8) = 8 - 8 = 0 (Done!).

    Total reads: only 3 steps to sum 13 numbers! At each step, you strip off one binary bit, taking at most O(log N) operations.

    B. Point Update: `i += (i & -i)`

    When you add delta to element i, which parent ranges need to be updated? Every index whose range covers i! You navigate up the tree simply by adding the lowest set bit: i += (i & -i)!


    Clean C++20 Implementation

    #include <vector>
    #include <cstdint>
    
    class FenwickTree {
        std::vector<int64_t> tree;
        int n;
    
        static inline int lowbit(int x) {
            return x & (-x);
        }
    
    public:
        FenwickTree(int size) : n(size), tree(size + 1, 0) {}
    
        // Adds delta to index i (1-indexed) in O(log N)
        void update(int i, int64_t delta) {
            while (i <= n) {
                tree[i] += delta;
                i += lowbit(i);
            }
        }
    
        // Computes sum of prefix [1 ... i] in O(log N)
        int64_t query(int i) const {
            int64_t sum = 0;
            while (i > 0) {
                sum += tree[i];
                i -= lowbit(i);
            }
            return sum;
        }
    
        // Computes range sum [l ... r] in O(log N)
        int64_t queryRange(int l, int r) const {
            if (l > r) return 0;
            return query(r) - query(l - 1);
        }
    };
    

    Why Fenwick Beats Segment Trees in Production

    MetricSegment TreeFenwick Tree
    Memory Overhead4N (or 2N)Strictly 1N (4x smaller)
    Implementation Size50-80 lines15 lines
    L1 Cache PerformanceModerateBlazing Fast (flat contiguous array)
    See less
    • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
  3. Asked: September 11, 2026In: Data Structures & Algorithms, System-Scale & Probabilistic Structures

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

    Abhay Tiwari
    Abhay Tiwari Begginer
    Added 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 couRead more

    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!
    See less
    • 0
    • 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

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