</>

307. Range Sum Query - Mutable

Medium
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Advanced Graphs
Time
—
Space
—

Standard Solution (C++)

SummaryGiven an integer array and a series of point-update and range-sum-query operations, build a data structure that supports updating a single element and returning the sum of elements over any subarray — both in sub-linear time.

Approach
  • Use a Fenwick Tree (Binary Indexed Tree), a compact array where each index stores a partial sum covering a range determined by its lowest set bit.
  • Build in O(n log n) by calling the point-update path for each element.
  • Update a single index by walking up the tree (add i & -i at each step), propagating the delta in O(log n).
  • Prefix sum queries walk down the tree (subtract i & -i) to accumulate partial sums; sumRange(l, r) is just prefix(r+1) - prefix(l).
#include <vector>
using namespace std;

class NumArray {
public:
    NumArray(vector<int>& nums) : n(nums.size()), bit(nums.size() + 1, 0), orig(nums) {
        // Build BIT by treating each element as a point update
        for (int i = 0; i < n; ++i)
            add(i + 1, nums[i]);
    }

    // Point update: set nums[index] to val
    void update(int index, int val) {
        int delta = val - orig[index];
        orig[index] = val;
        add(index + 1, delta);  // BIT is 1-indexed
    }

    // Range sum query [left, right] (0-indexed, inclusive)
    int sumRange(int left, int right) {
        return prefix(right + 1) - prefix(left);
    }

private:
    int n;
    vector<int> bit;   // 1-indexed Fenwick tree
    vector<int> orig;  // mirror of the original array to compute deltas on update

    // Add delta to 1-indexed position i and all ancestors
    void add(int i, int delta) {
        for (; i <= n; i += i & -i)
            bit[i] += delta;
    }

    // Sum of elements [1..i] in 1-indexed BIT
    int prefix(int i) {
        int s = 0;
        for (; i > 0; i -= i & -i)
            s += bit[i];
        return s;
    }
};
Time O(n log n) build, O(log n) per update and sumRange Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class NumArray {
public:
    NumArray(vector<int>& nums) {
        N=nums.size();
        tree.resize(N*4, 0);
        buildTree(nums, 1, 0, N-1);
    }
    
    void update(int index, int val) {
        updateTree(1, 0, N-1, index, val);
    }
    
    int sumRange(int left, int right) {
        return getSum(1, 0, N-1, left, right);
    }

private:
    vector<int> tree; // the index of root node is 1
    int N; // N is the size of the nums

    void buildTree(vector<int>& nums, int treeIdx, int start, int end) {
        if(start==end) {
            tree[treeIdx]=nums[start];
            return;
        }

        int mid=(start+end)/2;
        
        buildTree(nums, treeIdx*2, start, mid);
        buildTree(nums, treeIdx*2+1, mid+1, end);

        tree[treeIdx]=tree[treeIdx*2]+tree[treeIdx*2+1];
    }

    int getSum(int treeIdx, int curLeft, int curRight, int targetLeft, int targetRight) {
        if (curLeft>=targetLeft && curRight<= targetRight)
            return tree[treeIdx];
        else if (curRight<targetLeft || curLeft>targetRight)
            return 0;
        else {
            int mid=(curLeft+curRight)/2;
            return getSum(treeIdx*2, curLeft, mid, targetLeft, targetRight)+getSum(treeIdx*2+1, mid+1, curRight, targetLeft, targetRight);
        }
    }

    void updateTree(int treeIdx, int start, int end, int targetIdx, int val) {
        if (start==end) {
            tree[treeIdx]=val;
            return;
        }
        
        int mid=(start+end)/2;
        if (targetIdx<=mid) {
            updateTree(treeIdx*2, start, mid, targetIdx, val);
        }
        else {
            updateTree(treeIdx*2+1, mid+1, end, targetIdx, val);
        }

        tree[treeIdx]=tree[treeIdx*2]+tree[treeIdx*2+1];
    };
};

// Time: O(log N) for update and sumRange, O(N) for buildTree
// Space: O(4N) for the tree

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern