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

RTSALL Latest Articles

Abhishek
AbhishekBegginer
Asked: September 11, 20262026-09-11T09:53:23-05:00 2026-09-11T09:53:23-05:00In: 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)?

We need dynamic prefix sums and range sum queries over a stream of financial ledger transactions where numbers are constantly updated.

A standard array has O(1) update but O(N) range sum. A prefix sum array has O(1) range sum but O(N) update. Segment trees solve both in O(log N) but require 4N memory and complex pointer/tree logic. Peter Fenwick’s Binary Indexed Tree (BIT) solves both in O(log N) with zero tree nodes and only 1N memory using the bit trick i & (-i). How does this lowbit navigation work?

  • 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:27:27-05:00Added an answer on September 11, 2026 at 9:27 pm

    Here is the clean C++20 Fenwick Tree (BIT) implementation. It uses int64_t for precision and i & (-i) for logarithmic index jumps.

    Modern C++20 Solution (Fully Runnable)

    #include <iostream>
    #include <vector>
    #include <cstdint>
    
    class FenwickTree {
        int n;
        std::vector<int64_t> tree;
    
        static inline int lowbit(int x) noexcept {
            return x & (-x);
        }
    
    public:
        FenwickTree(int size) : n(size), tree(size + 1, 0) {}
    
        void add(int i, int64_t delta) {
            for (; i <= n; i += lowbit(i)) {
                tree[i] += delta;
            }
        }
    
        int64_t queryPrefix(int i) const {
            int64_t sum = 0;
            for (; i > 0; i -= lowbit(i)) {
                sum += tree[i];
            }
            return sum;
        }
    
        int64_t queryRange(int l, int r) const {
            if (l > r) return 0;
            return queryPrefix(r) - queryPrefix(l - 1);
        }
    };
    
    int main() {
        FenwickTree bit(10);
        bit.add(1, 5);
        bit.add(2, 3);
        bit.add(3, 7);
        bit.add(4, 2);
    
        std::cout << "Prefix sum [1..3]: " << bit.queryPrefix(3) << "n";  // 15
        std::cout << "Range sum [2..4]:  " << bit.queryRange(2, 4) << "n"; // 12
        return 0;
    }
    

    Complexity: O(log N) updates and queries with strictly 1N memory footprint.

    • 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:53:26-05:00Added 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 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)
    • 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.