Algo-Sim › Advanced Data Structures

Range Add, Range Sum (Lazy Propagation)

Hard · Advanced Data Structures · step through it in Java, Python and C++ on your own input

Add to a whole range in O(log n): tag the O(log n) nodes that cover it and push a tag to the children only when a later operation has to look inside.

Problem

Design a class built from an integer array nums that supports addRange(left, right, v), which adds v to every value in nums[left..right], and sumRange(left, right), which returns the sum of nums[left..right]. Both must run in O(log n), however wide the range.

Constraints

Edge cases to test

Follow-up questions

What else can be lazy?
Any update that composes and that a node can apply to its summary in O(1): range assign (tag = value), range add with range min or max (min += v), or both with an ordered tag.
Is there a simpler structure for this?
Two Fenwick trees support range add and range sum in O(log n) with less code, but they don’t extend to min, max or assignment.
Why push before splitting, not after?
The children are read next. Without the push their sums would miss the pending add, and the parent’s re-pull would lose it.

Solution

Java

class LazySegmentTree {
    private final int n;
    private final long[] sum, lazy;

    public LazySegmentTree(int[] nums) {
        n = nums.length;
        sum = new long[4 * n];
        lazy = new long[4 * n];  // a pending add for the whole range
        build(nums, 1, 0, n - 1);
    }

    private void build(int[] nums, int node, int lo, int hi) {
        if (lo == hi) { sum[node] = nums[lo]; return; }
        int mid = (lo + hi) / 2;
        build(nums, 2 * node, lo, mid);
        build(nums, 2 * node + 1, mid + 1, hi);
        sum[node] = sum[2 * node] + sum[2 * node + 1];
    }

    private void apply(int node, int lo, int hi, long v) {
        sum[node] += v * (hi - lo + 1);
        lazy[node] += v;
    }

    private void push(int node, int lo, int hi) {
        if (lazy[node] == 0) return;
        int mid = (lo + hi) / 2;
        apply(2 * node, lo, mid, lazy[node]);
        apply(2 * node + 1, mid + 1, hi, lazy[node]);
        lazy[node] = 0;
    }

    public void addRange(int left, int right, int v) {
        add(1, 0, n - 1, left, right, v);
    }

    private void add(int node, int lo, int hi, int l, int r, int v) {
        if (r < lo || hi < l) return;
        if (l <= lo && hi <= r) { apply(node, lo, hi, v); return; }
        push(node, lo, hi);
        int mid = (lo + hi) / 2;
        add(2 * node, lo, mid, l, r, v);
        add(2 * node + 1, mid + 1, hi, l, r, v);
        sum[node] = sum[2 * node] + sum[2 * node + 1];
    }

    public long sumRange(int left, int right) {
        return query(1, 0, n - 1, left, right);
    }

    private long query(int node, int lo, int hi, int l, int r) {
        if (r < lo || hi < l) return 0;
        if (l <= lo && hi <= r) return sum[node];
        push(node, lo, hi);
        int mid = (lo + hi) / 2;
        return query(2 * node, lo, mid, l, r) + query(2 * node + 1, mid + 1, hi, l, r);
    }
}

Python

class LazySegmentTree:
    def __init__(self, nums):
        self.n = len(nums)
        self.sum = [0] * (4 * self.n)
        self.lazy = [0] * (4 * self.n)  # a pending add for the whole range
        self._build(nums, 1, 0, self.n - 1)

    def _build(self, nums, node, lo, hi):
        if lo == hi:
            self.sum[node] = nums[lo]
            return
        mid = (lo + hi) // 2
        self._build(nums, 2 * node, lo, mid)
        self._build(nums, 2 * node + 1, mid + 1, hi)
        self.sum[node] = self.sum[2 * node] + self.sum[2 * node + 1]

    def _apply(self, node, lo, hi, v):
        self.sum[node] += v * (hi - lo + 1)
        self.lazy[node] += v

    def _push(self, node, lo, hi):
        if self.lazy[node] == 0:
            return
        mid = (lo + hi) // 2
        self._apply(2 * node, lo, mid, self.lazy[node])
        self._apply(2 * node + 1, mid + 1, hi, self.lazy[node])
        self.lazy[node] = 0

    def addRange(self, left, right, v):
        self._add(1, 0, self.n - 1, left, right, v)

    def _add(self, node, lo, hi, l, r, v):
        if r < lo or hi < l:
            return
        if l <= lo and hi <= r:
            self._apply(node, lo, hi, v)
            return
        self._push(node, lo, hi)
        mid = (lo + hi) // 2
        self._add(2 * node, lo, mid, l, r, v)
        self._add(2 * node + 1, mid + 1, hi, l, r, v)
        self.sum[node] = self.sum[2 * node] + self.sum[2 * node + 1]

    def sumRange(self, left, right):
        return self._query(1, 0, self.n - 1, left, right)

    def _query(self, node, lo, hi, l, r):
        if r < lo or hi < l:
            return 0
        if l <= lo and hi <= r:
            return self.sum[node]
        self._push(node, lo, hi)
        mid = (lo + hi) // 2
        return self._query(2 * node, lo, mid, l, r) + self._query(2 * node + 1, mid + 1, hi, l, r)

C++

#include <bits/stdc++.h>
using namespace std;

class LazySegmentTree {
  public:
    int n;
    vector<long long> sum, lazy;

    LazySegmentTree(vector<int> &nums) {
        n = int(nums.size());
        sum.assign(4 * n, 0);
        lazy.assign(4 * n, 0);
        build(nums, 1, 0, n - 1);
    }

    void build(vector<int> &nums, int node, int lo, int hi) {
        if (lo == hi) { sum[node] = nums[lo]; return; }
        int mid = (lo + hi) / 2;
        build(nums, 2 * node, lo, mid);
        build(nums, 2 * node + 1, mid + 1, hi);
        sum[node] = sum[2 * node] + sum[2 * node + 1];
    }

    void apply(int node, int lo, int hi, long long v) {
        sum[node] += v * (hi - lo + 1);
        lazy[node] += v;
    }

    void push(int node, int lo, int hi) {
        if (lazy[node] == 0) return;
        int mid = (lo + hi) / 2;
        apply(2 * node, lo, mid, lazy[node]);
        apply(2 * node + 1, mid + 1, hi, lazy[node]);
        lazy[node] = 0;
    }

    void addRange(int left, int right, int v) {
        add(1, 0, n - 1, left, right, v);
    }

    void add(int node, int lo, int hi, int l, int r, int v) {
        if (r < lo || hi < l) return;
        if (l <= lo && hi <= r) { apply(node, lo, hi, v); return; }
        push(node, lo, hi);
        int mid = (lo + hi) / 2;
        add(2 * node, lo, mid, l, r, v);
        add(2 * node + 1, mid + 1, hi, l, r, v);
        sum[node] = sum[2 * node] + sum[2 * node + 1];
    }

    long long sumRange(int left, int right) {
        return query(1, 0, n - 1, left, right);
    }

    long long query(int node, int lo, int hi, int l, int r) {
        if (r < lo || hi < l) return 0;
        if (l <= lo && hi <= r) return sum[node];
        push(node, lo, hi);
        int mid = (lo + hi) / 2;
        return query(2 * node, lo, mid, l, r) + query(2 * node + 1, mid + 1, hi, l, r);
    }
};

More Advanced Data Structures problems