Answer sums and minimums over ranges that change, with the segment-tree idea.
You work on the dashboard of a small shop. The shop records its takings for each hour of the day, in whole units. Managers ask many questions, such as "what did we take between hour 2 and hour 5?". Late sales also arrive, and each one adds to the takings of one hour that has already passed.
Here are eight hours of takings. Hours count from 0.
| Hour | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Takings | 5 | 3 | 7 | 9 | 6 | 4 | 2 | 8 |
A range query asks for one answer about a stretch of consecutive positions: the total, the smallest value or the largest. The stretch is written as left to right, and both ends are included. Hours 2 to 5 total 7 + 9 + 6 + 4 = 26.
The first attempt is correct. For every question, add up the hours from left to right. A day of 100,000 hours and 100,000 questions costs up to 100,000 × 100,000 = 10,000,000,000 additions, because a question can span the whole day. That is far more than a page can wait for.
You met a fix in Prefix sums in 1D and 2D. Build prefix[i], the total of the first i hours, once. Then any total is prefix[right + 1] - prefix[left], which is two reads.
For the eight hours, prefix is 0, 5, 8, 15, 24, 30, 34, 36, 44. Hours 2 to 5 give prefix[6] - prefix[2] = 34 - 8 = 26. Each question now costs O(1).
The trouble starts with a late sale. Add 4 to hour 2, and every entry from prefix[3] onwards grows by 4: that is 6 of the 8 entries. A change at hour 0 rewrites all 8.
For 100,000 hours, one change can rewrite 100,000 entries. And 100,000 changes cost 10,000,000,000 rewrites again.
So you face a trade. Without prefix sums a question is slow. With them a change is slow. We want both to take about log n steps: 17 for 100,000 hours.
A bookkeeper keeps a ledger of eight daily pages. A running grand total after every page is fast to read. But a late correction on page 2 forces her to rewrite the total on every page after it. Keeping no totals at all makes every question a long addition.
Instead she writes a subtotal for each block of pages: pages 1 and 2, pages 3 and 4, pages 1 to 4, and so on. A question adds a few blocks. A correction updates only the few blocks that contain that page.
The picture is wrong in one way. A bookkeeper chooses blocks by habit. The structures in this lesson use a fixed rule for the blocks, so a program always knows which few to read and which few to change.
A ledger with subtotals shows the idea: a question adds a few blocks and a correction touches a few. A program needs a fixed rule for the blocks.
This lesson shows four ways to pick those blocks. A Fenwick tree answers sums with point changes in a few lines of code. A segment tree does the same for any combine rule, such as the minimum. With lazy propagation on its nodes it also changes a whole range at once.
A sparse table gives instant minimums when nothing ever changes. A table at the end tells you which to choose.
Predict what happens
Q The eight hours have prefix sums 0, 5, 8, 15, 24, 30, 34, 36, 44. A late sale adds 4 to hour 0. How many of the entries from prefix[1] to prefix[8] change?
Answer: C
Entry i holds the total of the first i hours, and hour 0 is in every one of them. All 8 entries grow by 4. With 100,000 hours, a change at hour 0 rewrites 100,000 entries.
A Fenwick tree is an array tree with one entry for each position, counted from 1. Hour h of the shop is position h + 1. The lowest set bit of a position i is written lowbit(i) and computed as i & -i. It decides the block that entry i holds: the last lowbit(i) values up to position i.
Positions 1 to 8 for the eight hours:
| Position i | In binary | lowbit(i) | Hours it holds (positions) | tree[i] |
|---|---|---|---|---|
| 1 | 001 | 1 | 1 to 1 | 5 |
| 2 | 010 | 2 | 1 to 2 | 8 |
| 3 | 011 | 1 | 3 to 3 | 7 |
| 4 | 100 | 4 | 1 to 4 | 24 |
| 5 | 101 | 1 | 5 to 5 | 6 |
| 6 | 110 | 2 | 5 to 6 | 10 |
| 7 | 111 | 1 | 7 to 7 | 2 |
| 8 | 1000 | 8 | 1 to 8 | 44 |
Odd positions hold one value. Position 6 holds positions 5 and 6, and position 8 holds everything.
The total of the first 7 positions needs only the blocks that tile 1 to 7. Start at 7 and take tree[7] = 2, which covers position 7. Clear the lowest set bit: 7 becomes 6.
Take tree[6] = 10, which covers positions 5 and 6. Clear again: 6 becomes 4. Take tree[4] = 24, which covers 1 to 4. Clear again and you reach 0, so stop.
The three blocks give 2 + 10 + 24 = 36, and prefix[7] is 36. A range total uses two such walks: the walk for right + 1, minus the walk for left. For hours 2 to 5 that is the walk for 6, which totals 34 from blocks 6 and 4, minus the walk for 2, which totals 8. The answer is 26.
Exercise · Predict the output: Which blocks does a query read?. A Fenwick tree has 13 or more positions. The program lists the entries a query for position 13 reads. What does it print?
tree_index = 13
visited = []
while tree_index > 0:
visited.append(tree_index)
tree_index -= tree_index & -tree_index
print(*visited)A late sale at position 3 must reach every block that contains position 3. Start at 3 and add 4 to tree[3]. Add the lowest set bit: 3 + 1 is 4, so add to tree[4].
Then 4 + 4 is 8, so add to tree[8]. Then 8 + 8 is 16, which is past the end, so stop.
Three entries changed: tree[3] becomes 11, tree[4] becomes 28 and tree[8] becomes 48. The prefix array would have rewritten 6 entries for the same change.
A query walks the set bits of its position, one block for each. The visualizer shows the same loop: it starts from a position, shows x, x - 1 and x & (x - 1), and clears the lowest set bit until nothing is left. The value x & (x - 1) equals x - lowbit(x), so each step of the visualizer is one block of a Fenwick query.
Try these four, in order:
x & -x keeps.Step by step: A Fenwick query for position 44, one block at a time. The animated player loads in your browser.
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
A Fenwick tree stores sums well, but its blocks depend on a bit trick. A segment tree stores the answer for halves. The root holds the whole range. Each node splits its range into a left half and a right half, down to single hours.
For the eight hours, with each node showing its total, the nodes in order from the root are:
| Node | Hours | Total |
|---|---|---|
| 1 | 0 to 7 | 44 |
| 2 | 0 to 3 | 24 |
| 3 | 4 to 7 | 20 |
| 4 | 0 to 1 | 8 |
| 5 | 2 to 3 | 16 |
| 6 | 4 to 5 | 10 |
| 7 | 6 to 7 | 10 |
A node i has children 2i and 2i + 1. The leaves are nodes 8 to 15, and they hold 5, 3, 7, 9, 6, 4, 2, 8.
A range question asks each node one of three things. If the node's hours lie outside the range, it adds nothing. If they lie wholly inside, take its total and stop. If they only overlap, ask both children.
For hours 2 to 5, the root overlaps, so ask node 2 and node 3. Node 2 (hours 0 to 3) overlaps, so ask nodes 4 and 5. Node 4 is outside. Node 5 (hours 2 to 3) is inside: take 16.
Node 3 (hours 4 to 7) overlaps, so ask nodes 6 and 7. Node 6 (hours 4 to 5) is inside: take 10. Node 7 is outside. The answer is 16 + 10 = 26, found by visiting 7 of the 15 nodes.
A range question on a segment tree takes the nodes that lie wholly inside the range. At most two nodes on each level are asked further.
A point update changes one leaf and then recomputes each ancestor on the way up. Adding 4 to hour 2 changes nodes 10, 5, 2 and 1: one node on each level, so 4 nodes for 8 hours.
Predict what happens
Q In the eight-hour segment tree, a question asks for hours 4 to 7. From how many nodes does it take a total?
Answer: B
Node 3 covers exactly hours 4 to 7, so its total of 20 is the answer, and the question stops there. A node that lies wholly inside the range is taken without looking at its children.
Every entry of the tree holds the combined value of one fixed block of hours. A query or an update touches at most one block on each level, so about log n blocks.
Entry i holds the half-open block from i - lowbit(i) up to i. Clearing the lowest set bit of i gives exactly i - lowbit(i), which is the start of that block. The next block therefore ends where this one starts, and the blocks join end to end with no gap and no overlap, until the position reaches 0.
A position with b set bits has b blocks, so a query takes at most as many steps as the position has set bits. For up to 100,000 positions the most any query takes is 16, at position 65,535, which is sixteen 1 bits.
An update does the opposite walk. Adding lowbit(i) to i moves to the next entry whose block contains position i, and each step at least doubles the lowbit. So the walk ends after at most about log n steps: for 100,000 positions, the longest update walk takes 17 steps.
Positions count from 1 for a reason. Position 0 has no set bit, so 0 + (0 & -0) is 0 and an update walk would never move.
def fenwick_totals(values, ops):
n = len(values)
# [1] Build: tree[i] holds the total of the last lowbit(i) hours up to hour i, with hours counted from 1.
tree = [0] * (n + 1)
for i in range(1, n + 1):
tree[i] += values[i - 1]
parent = i + (i & -i)
if parent <= n:
tree[parent] += tree[i]
answers = []
for kind, a, b in ops:
if kind == 0:
# [2] Update: add b to hour a, then to every block that holds it, jumping up by the lowest set bit.
i = a + 1
while i <= n:
tree[i] += b
i += i & -i
else:
# [3] Query: the total of hours 0 to b is the blocks reached by clearing the lowest set bit each time.
total = 0
i = b + 1
while i > 0:
total += tree[i]
i -= i & -i
# [4] Subtract the total of the hours before a, found the same way, to leave hours a to b.
i = a
while i > 0:
total -= tree[i]
i -= i & -i
# [5] Record the answer to this question.
answers.append(total)
return answerspublic long[] fenwickTotals(int[] values, int[][] ops) {
int n = values.length;
// [1] Build: tree[i] holds the total of the last lowbit(i) hours up to hour i, with hours counted from 1.
long[] tree = new long[n + 1];
for (int i = 1; i <= n; i++) {
tree[i] += values[i - 1];
int parent = i + (i & -i);
if (parent <= n) {
tree[parent] += tree[i];
}
}
long[] answers = new long[ops.length];
int found = 0;
for (int[] op : ops) {
if (op[0] == 0) {
// [2] Update: add b to hour a, then to every block that holds it, jumping up by the lowest set bit.
int i = op[1] + 1;
while (i <= n) {
tree[i] += op[2];
i += i & -i;
}
} else {
// [3] Query: the total of hours 0 to b is the blocks reached by clearing the lowest set bit each time.
long total = 0;
int i = op[2] + 1;
while (i > 0) {
total += tree[i];
i -= i & -i;
}
// [4] Subtract the total of the hours before a, found the same way, to leave hours a to b.
i = op[1];
while (i > 0) {
total -= tree[i];
i -= i & -i;
}
// [5] Record the answer to this question.
answers[found++] = total;
}
}
return java.util.Arrays.copyOf(answers, found);
}vector<long long> fenwickTotals(vector<int> values, vector<vector<int>> ops) {
int n = values.size();
// [1] Build: tree[i] holds the total of the last lowbit(i) hours up to hour i, with hours counted from 1.
vector<long long> tree(n + 1, 0);
for (int i = 1; i <= n; i++) {
tree[i] += values[i - 1];
int parent = i + (i & -i);
if (parent <= n) {
tree[parent] += tree[i];
}
}
vector<long long> answers;
for (auto& op : ops) {
if (op[0] == 0) {
// [2] Update: add b to hour a, then to every block that holds it, jumping up by the lowest set bit.
int i = op[1] + 1;
while (i <= n) {
tree[i] += op[2];
i += i & -i;
}
} else {
// [3] Query: the total of hours 0 to b is the blocks reached by clearing the lowest set bit each time.
long long total = 0;
int i = op[2] + 1;
while (i > 0) {
total += tree[i];
i -= i & -i;
}
// [4] Subtract the total of the hours before a, found the same way, to leave hours a to b.
i = op[1];
while (i > 0) {
total -= tree[i];
i -= i & -i;
}
// [5] Record the answer to this question.
answers.push_back(total);
}
}
return answers;
}function fenwickTotals(values, ops) {
const n = values.length;
// [1] Build: tree[i] holds the total of the last lowbit(i) hours up to hour i, with hours counted from 1.
const tree = new Array(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
tree[i] += values[i - 1];
const parent = i + (i & -i);
if (parent <= n) {
tree[parent] += tree[i];
}
}
const answers = [];
for (const [kind, a, b] of ops) {
if (kind === 0) {
// [2] Update: add b to hour a, then to every block that holds it, jumping up by the lowest set bit.
let i = a + 1;
while (i <= n) {
tree[i] += b;
i += i & -i;
}
} else {
// [3] Query: the total of hours 0 to b is the blocks reached by clearing the lowest set bit each time.
let total = 0;
let i = b + 1;
while (i > 0) {
total += tree[i];
i -= i & -i;
}
// [4] Subtract the total of the hours before a, found the same way, to leave hours a to b.
i = a;
while (i > 0) {
total -= tree[i];
i -= i & -i;
}
// [5] Record the answer to this question.
answers.push(total);
}
}
return answers;
}Exercise · Find the bug: The walk that stops one position early. This function builds a Fenwick tree and returns the total of hours `left` to `right`. It returns too little for some ranges. Which line is wrong?
def range_total(values, left, right):
n = len(values)
tree = [0] * (n + 1)
for hour in range(n):
i = hour + 1
while i <= n:
tree[i] += values[hour]
i += i & -i
total = 0
i = right + 1
while i > 1:
total += tree[i]
i -= i & -i
i = left
while i > 0:
total -= tree[i]
i -= i & -i
return totalOn each level the nodes split the hours into equal pieces. A range has two edges, and each edge crosses at most one node that only partly overlaps the range. Every other node is wholly inside or wholly outside, and a question stops there. So at most two nodes on each level are asked further, and at most two on each level are taken.
For 256 hours the tree has 8 levels below the root. Running every one of the 32,896 ranges, the most nodes any question visits is 31, which is below 4 × 8 = 32. For 100,000 hours a leaf is 17 steps below the root, so a question takes O(log n) node visits.
The code below stores the tree in one array with the leaves at positions n to 2n - 1 and the parent of position i at i >> 1. This is the same tree, built from the bottom, and it works for any n, not only powers of two. Its query walks the two ends of the range upwards together and takes a node whenever it lies wholly inside. A point update rewrites one leaf and the ancestors above it, one on each level.
def segment_minimums(values, ops):
n = len(values)
# [1] Build: the leaves sit at positions n to 2n - 1, and each parent holds the minimum of its two children.
tree = [0] * (2 * n)
for i in range(n):
tree[n + i] = values[i]
for i in range(n - 1, 0, -1):
tree[i] = min(tree[2 * i], tree[2 * i + 1])
answers = []
for kind, a, b in ops:
if kind == 0:
# [2] Update: replace one leaf, then recompute every ancestor on the way up to the root.
i = a + n
tree[i] = b
while i > 1:
i >>= 1
tree[i] = min(tree[2 * i], tree[2 * i + 1])
else:
# [3] Query: climb both ends of the range together, taking a node whenever it lies wholly inside the range.
best = 2147483647
low = a + n
high = b + n + 1
while low < high:
if low & 1:
best = min(best, tree[low])
low += 1
if high & 1:
high -= 1
best = min(best, tree[high])
low >>= 1
high >>= 1
# [4] Record the answer to this question.
answers.append(best)
return answerspublic int[] segmentMinimums(int[] values, int[][] ops) {
int n = values.length;
// [1] Build: the leaves sit at positions n to 2n - 1, and each parent holds the minimum of its two children.
int[] tree = new int[2 * n];
for (int i = 0; i < n; i++) {
tree[n + i] = values[i];
}
for (int i = n - 1; i > 0; i--) {
tree[i] = Math.min(tree[2 * i], tree[2 * i + 1]);
}
int[] answers = new int[ops.length];
int found = 0;
for (int[] op : ops) {
if (op[0] == 0) {
// [2] Update: replace one leaf, then recompute every ancestor on the way up to the root.
int i = op[1] + n;
tree[i] = op[2];
while (i > 1) {
i >>= 1;
tree[i] = Math.min(tree[2 * i], tree[2 * i + 1]);
}
} else {
// [3] Query: climb both ends of the range together, taking a node whenever it lies wholly inside the range.
int best = 2147483647;
int low = op[1] + n;
int high = op[2] + n + 1;
while (low < high) {
if ((low & 1) == 1) {
best = Math.min(best, tree[low]);
low++;
}
if ((high & 1) == 1) {
high--;
best = Math.min(best, tree[high]);
}
low >>= 1;
high >>= 1;
}
// [4] Record the answer to this question.
answers[found++] = best;
}
}
return java.util.Arrays.copyOf(answers, found);
}vector<int> segmentMinimums(vector<int> values, vector<vector<int>> ops) {
int n = values.size();
// [1] Build: the leaves sit at positions n to 2n - 1, and each parent holds the minimum of its two children.
vector<int> tree(2 * n, 0);
for (int i = 0; i < n; i++) {
tree[n + i] = values[i];
}
for (int i = n - 1; i > 0; i--) {
tree[i] = min(tree[2 * i], tree[2 * i + 1]);
}
vector<int> answers;
for (auto& op : ops) {
if (op[0] == 0) {
// [2] Update: replace one leaf, then recompute every ancestor on the way up to the root.
int i = op[1] + n;
tree[i] = op[2];
while (i > 1) {
i >>= 1;
tree[i] = min(tree[2 * i], tree[2 * i + 1]);
}
} else {
// [3] Query: climb both ends of the range together, taking a node whenever it lies wholly inside the range.
int best = 2147483647;
int low = op[1] + n;
int high = op[2] + n + 1;
while (low < high) {
if (low & 1) {
best = min(best, tree[low]);
low++;
}
if (high & 1) {
high--;
best = min(best, tree[high]);
}
low >>= 1;
high >>= 1;
}
// [4] Record the answer to this question.
answers.push_back(best);
}
}
return answers;
}function segmentMinimums(values, ops) {
const n = values.length;
// [1] Build: the leaves sit at positions n to 2n - 1, and each parent holds the minimum of its two children.
const tree = new Array(2 * n).fill(0);
for (let i = 0; i < n; i++) {
tree[n + i] = values[i];
}
for (let i = n - 1; i > 0; i--) {
tree[i] = Math.min(tree[2 * i], tree[2 * i + 1]);
}
const answers = [];
for (const [kind, a, b] of ops) {
if (kind === 0) {
// [2] Update: replace one leaf, then recompute every ancestor on the way up to the root.
let i = a + n;
tree[i] = b;
while (i > 1) {
i >>= 1;
tree[i] = Math.min(tree[2 * i], tree[2 * i + 1]);
}
} else {
// [3] Query: climb both ends of the range together, taking a node whenever it lies wholly inside the range.
let best = 2147483647;
let low = a + n;
let high = b + n + 1;
while (low < high) {
if (low & 1) {
best = Math.min(best, tree[low]);
low++;
}
if (high & 1) {
high--;
best = Math.min(best, tree[high]);
}
low >>= 1;
high >>= 1;
}
// [4] Record the answer to this question.
answers.push(best);
}
}
return answers;
}Now a promotion adds 5 to every hour from 2 to 5, and questions follow. Updating six leaves one by one costs O(n) again. Lazy propagation avoids it with one idea: do not push the update all the way down.
Stop at the nodes that lie wholly inside the range. Add the update to their total, and leave a tag that says "every hour below this node still owes 5".
For hours 2 to 5, the nodes that lie wholly inside are node 5 (hours 2 to 3) and node 6 (hours 4 to 5). Each hour in the range gains 5, so node 5 gains 5 × 2 = 10 and node 6 gains 10.
| Node | Hours | Total before | Tag after | Total after |
|---|---|---|---|---|
| 5 | 2 to 3 | 16 | 5 | 26 |
| 6 | 4 to 5 | 10 | 5 | 20 |
| 2 | 0 to 3 | 24 | none | 34 |
| 3 | 4 to 7 | 20 | none | 30 |
| 1 | 0 to 7 | 44 | none | 64 |
The ancestors of the two nodes recompute their totals from their children. The children of node 5 and node 6 still hold their old values. The tag is their debt.
A later question looks inside a tagged node only when it must. Take the total of hours 3 to 6, which is 36 after the update. The question needs hour 3, a leaf below node 5.
Before it descends into node 5, it pushes the tag down. Each child of node 5 adds 5 times its size to its total and takes the tag, and node 5's tag is cleared. Hour 3 is now 9 + 5 = 14.
The question adds 14, then node 6's total of 20, then hour 6, which is 2. That gives 14 + 20 + 2 = 36.
The rule for correctness is short: never read or change below a node without first pushing its tag down. A node's own total is always right, so a question that stops at a node never needs its children.
A tag on a node means its children still owe an update, so the tag is pushed down before anything looks inside the node.
Predict what happens
Q A tag of 5 sits on node 5, which covers hours 2 and 3. Before the update they were worth 7 and 9. A question needs only hour 2. What must happen first?
Answer: B
A tagged node knows its own total, but its children have not seen the update, so hour 2 still holds 7. Pushing the tag adds 5 to each child, and hour 2 reads 12. Without the push, the question would read an old value.
A sparse table works when nothing changes. Level 0 holds the values. Level k holds the minimum of every block of 2^k values, and each such block is the minimum of two blocks of level k - 1. For the eight hours the levels are:
| Level | Block size | Minimums, one for each start |
|---|---|---|
| 0 | 1 | 5, 3, 7, 9, 6, 4, 2, 8 |
| 1 | 2 | 3, 3, 7, 6, 4, 2, 2 |
| 2 | 4 | 3, 3, 4, 2, 2 |
| 3 | 8 | 2 |
To find the minimum of hours 2 to 4, the length is 3. The biggest block that fits has 2 values, which is level 1. Take the block that starts at 2 (minimum 7) and the block that ends at 4, which starts at 3 (minimum 6). The two blocks overlap at hour 3, and the answer is the smaller one: 6.
The overlap is safe because of one property. Taking the minimum of a value with itself changes nothing: min(x, x) = x. An operation with that property is idempotent.
Minimum, maximum, gcd and bitwise AND and OR are idempotent. A sum is not: counting hour 3 twice gives the wrong total.
The level is the position of the highest set bit of the length. For a length of 3 that is binary 11, so the level is 1. Each question reads two table cells, so a question is O(1).
The table has one row for each level and about n cells on each row. For 100,000 values there are 17 levels and 1,568,946 cells in all.
def sparse_minimums(values, ranges):
n = len(values)
# [1] Level k holds the minimum of every block of 2^k hours, built from two blocks of level k - 1.
levels = n.bit_length()
table = [values[:]]
for level in range(1, levels):
below = table[level - 1]
half = 1 << (level - 1)
table.append([min(below[i], below[i + half]) for i in range(n - (1 << level) + 1)])
answers = []
for left, right in ranges:
# [2] Pick the biggest level whose blocks fit in the range: the highest set bit of the length.
k = (right - left + 1).bit_length() - 1
# [3] Two blocks of that size, one at each end, cover the range. Where they overlap the minimum is unchanged.
answers.append(min(table[k][left], table[k][right - (1 << k) + 1]))
return answerspublic int[] sparseMinimums(int[] values, int[][] ranges) {
int n = values.length;
// [1] Level k holds the minimum of every block of 2^k hours, built from two blocks of level k - 1.
int levels = 32 - Integer.numberOfLeadingZeros(n);
int[][] table = new int[levels][];
table[0] = values.clone();
for (int level = 1; level < levels; level++) {
int half = 1 << (level - 1);
table[level] = new int[n - (1 << level) + 1];
for (int i = 0; i < table[level].length; i++) {
table[level][i] = Math.min(table[level - 1][i], table[level - 1][i + half]);
}
}
int[] answers = new int[ranges.length];
for (int q = 0; q < ranges.length; q++) {
int left = ranges[q][0];
int right = ranges[q][1];
// [2] Pick the biggest level whose blocks fit in the range: the highest set bit of the length.
int k = 31 - Integer.numberOfLeadingZeros(right - left + 1);
// [3] Two blocks of that size, one at each end, cover the range. Where they overlap the minimum is unchanged.
answers[q] = Math.min(table[k][left], table[k][right - (1 << k) + 1]);
}
return answers;
}vector<int> sparseMinimums(vector<int> values, vector<vector<int>> ranges) {
int n = values.size();
// [1] Level k holds the minimum of every block of 2^k hours, built from two blocks of level k - 1.
int levels = 32 - __builtin_clz(n);
vector<vector<int>> table(levels);
table[0] = values;
for (int level = 1; level < levels; level++) {
int half = 1 << (level - 1);
table[level].resize(n - (1 << level) + 1);
for (int i = 0; i < (int)table[level].size(); i++) {
table[level][i] = min(table[level - 1][i], table[level - 1][i + half]);
}
}
vector<int> answers;
for (auto& range : ranges) {
int left = range[0];
int right = range[1];
// [2] Pick the biggest level whose blocks fit in the range: the highest set bit of the length.
int k = 31 - __builtin_clz(right - left + 1);
// [3] Two blocks of that size, one at each end, cover the range. Where they overlap the minimum is unchanged.
answers.push_back(min(table[k][left], table[k][right - (1 << k) + 1]));
}
return answers;
}function sparseMinimums(values, ranges) {
const n = values.length;
// [1] Level k holds the minimum of every block of 2^k hours, built from two blocks of level k - 1.
const levels = 32 - Math.clz32(n);
const table = [values.slice()];
for (let level = 1; level < levels; level++) {
const half = 1 << (level - 1);
const row = [];
for (let i = 0; i + (1 << level) <= n; i++) {
row.push(Math.min(table[level - 1][i], table[level - 1][i + half]));
}
table.push(row);
}
const answers = [];
for (const [left, right] of ranges) {
// [2] Pick the biggest level whose blocks fit in the range: the highest set bit of the length.
const k = 31 - Math.clz32(right - left + 1);
// [3] Two blocks of that size, one at each end, cover the range. Where they overlap the minimum is unchanged.
answers.push(Math.min(table[k][left], table[k][right - (1 << k) + 1]));
}
return answers;
}Predict what happens
Q Using the sparse table above, what is the minimum of hours 1 to 6 of the eight values 5, 3, 7, 9, 6, 4, 2, 8?
Answer: B
The length is 6, so the level is 2 and each block has 4 hours. The block from hour 1 has minimum 3, and the block from hour 3 has minimum 2. They overlap on hours 3 and 4, and the answer is 2.
Now write it yourself. The lab has one function, shop_totals(takings, ops). Each operation is [kind, a, b].
[0, a, b] is a late sale: add b to the takings of hour a.[1, a, b] is a question: what is the total of hours a to b, both included?Return the answers to the questions, in the order they were asked. Return an empty list when there is no question. Totals can pass 2 billion, so use 64-bit numbers in Java and C++.
For the eight hours and the operations [[1, 0, 7], [0, 2, 4], [1, 2, 5]], the answers are [44, 30]. The first question gives 44. The late sale makes hour 2 worth 11, and then hours 2 to 5 total 11 + 9 + 6 + 4 = 30.
Before the lab, arrange the lines of the walk that does the hard part. Use the tree in the table above, counted from position 1.
Exercise · Put it in order: Read a range from a built tree. Arrange the lines into a function that takes a Fenwick tree (position 0 unused) and returns the total of hours `left` to `right`, counted from hour 0.
def range_total_from(tree, left, right):
total = 0
i = right + 1
while i > 0:
total += tree[i]
i -= i & -i
i = left
while i > 0:
total -= tree[i]
i -= i & -i
return total
i = left + 1Three rules keep it correct:
i -= i & -i. An update walk adds it with i += i & -i.left to right, subtract the walk that starts at position left, not at left - 1.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
For n values and one question or change at a time. The step counts are for 100,000 values, and they come from running the walks.
| Question | Prefix sums | Fenwick tree | Segment tree | Segment tree with lazy propagation | Sparse table |
|---|---|---|---|---|---|
| Build time | O(n) | O(n) | O(n) | O(n) | O(n log n) |
| Query time | O(1): 2 reads | O(log n): at most 16 reads for each of two walks | O(log n): at most 36 reads | O(log n) | O(1): 2 reads |
| Update time | O(n): up to 100,000 rewrites | O(log n): at most 17 writes | O(log n): at most 18 writes | O(log n), also for a whole range | O(n): a rebuild is 1,568,946 cells |
| Memory | O(n) | O(n): n + 1 cells | O(n): 2n cells | O(n): totals and tags | O(n log n): 1,568,946 cells |
| Combine rules | Sums, and anything that can be undone | Sums, and anything that can be undone | Any associative rule: sum, minimum, gcd | Any rule that a tag can apply to a block | Idempotent rules only: minimum, maximum, gcd |
| Use it when | Nothing changes and the question is a total | Single values change and the question is a total | Single values change and the rule is not a sum | Whole ranges change | Nothing changes and the rule is a minimum or maximum |
A short way to decide: ask what changes, and what the question asks.
Use these structures when changes and questions arrive mixed together and both are many. A dashboard of takings, a counter of events per minute and a game map whose region totals change all fit. So does a leaderboard that asks how many players score below a value.
Counting fits the Fenwick tree well. Keep one cell for each score, add 1 when a player scores, and a prefix query then counts the players at or below a score. Words such as "so far", "in this stretch", "after each change" and "at any moment" are the hint.
Do not build a tree when the values never change and the question is a total. Prefix sums are shorter and give O(1). Do not use a sparse table when values change, because every change forces a rebuild.
Do not use any of them when there are only a handful of questions. A loop over the stretch for each question is correct, has no structure to get wrong, and is fast enough for 1,000 questions over 1,000 values. Reach for a tree when the product of the questions and the stretch length is too big.
i = hour makes the update walk start at position 0 for hour 0. Then i += i & -i adds 0, so i stays at 0 and the loop never ends. The same call with i = hour + 1 ends after at most 17 steps for 100,000 hours. Count positions from 1 in the tree and keep hours from 0 outside it.
For a top-down tree with the root at 1 and children at 2 * i and 2 * i + 1, tree = [0] * (2 * n) is too small when n is not a power of two. For 6 hours the highest node number is 13, and a list of 12 cells ends at 11. The call raises an IndexError. Allocate 4 * n cells for the top-down layout, or use the bottom-up layout above, where 2 * n is exact.
Add 5 to hours 2 and 3 in an 8-hour tree, and the tag sits on node 5. A question for hour 2 alone that descends into node 5 without push_down(node) reads the old leaf, which is 7. The right answer is 12. Every function that looks inside a node, whether a question or a later update, pushes the tag first.
A sparse table answers in O(1), so it looks like the best choice. With 100,000 values, one call to build_table(values) fills 1,568,946 cells, and 100,000 changes cost 156,894,600,000 cells. A Fenwick or segment tree does the same job in about 17 steps for each change.
Two blocks that overlap are safe for a minimum and wrong for a total, because the overlap is counted twice. Swapping min for + in table[k][left] + table[k][right - (1 << k) + 1] makes that mistake. On the values 5, 3, 7, 9, the total of hours 0 to 2 is 15. But the blocks of hours 0 to 1 and hours 1 to 2 give 8 + 10 = 18.
Use a sparse table only for minimum, maximum, gcd and other idempotent rules.
Overlapping blocks are safe for a minimum but count a value twice in a sum: 18 instead of 15 for hours 0 to 2.
Hours count from 0, but tree positions count from 1. So the hours before left end at position left, and starting the second walk at left - 1 keeps hour left - 1 in the total.
On the values 5, 3, 7, 9 and the range 1 to 2, the walk starts at 0 and removes nothing. It returns 15 where 3 + 7 = 10 is right. For left equal to 0 the mistake hides, because there is nothing to remove. Try to find where it shows.
Exercise · Break it: Find the range that counts an extra hour. This function builds a Fenwick tree and returns the total of hours `left` to `right`, both included, counting hours from 0. Find values and a range where it returns the wrong total.
def total_between(values, left, right):
n = len(values)
tree = [0] * (n + 1)
for hour in range(n):
i = hour + 1
while i <= n:
tree[i] += values[hour]
i += i & -i
total = 0
i = right + 1
while i > 0:
total += tree[i]
i -= i & -i
i = left - 1
while i > 0:
total -= tree[i]
i -= i & -i
return totallowbit(i) values. A query clears the lowest set bit again and again. An update adds it again and again. Positions count from 1.Explain in your own words why a query on a Fenwick tree needs at most log n blocks, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Why prefix sums stop
Q A day has 100,000 hours, and prefix sums are built once. A late sale changes hour 0. How many prefix entries can change?
Answer: C
Prefix entry i holds the total of the first i hours, so a change at hour 0 changes every entry. That is why mixed changes and questions need a tree: both cost about 17 steps for 100,000 hours.
Checkpoint · The Fenwick tree
Q1/2 In a Fenwick tree, what does entry 12 hold? Positions count from 1, and 12 is 1100 in binary.
Answer: C
The lowest set bit of 12 is 4, so entry 12 holds the last 4 values up to position 12: positions 9, 10, 11 and 12.
Q2/2 A query for position 13 reads entry 13. Which entries does it read next?
Answer: C
A query clears the lowest set bit each time: 13 is 1101, then 1100 is 12, then 1000 is 8, then 0. Adding the lowest bit instead would be an update walk.
Checkpoint · Fenwick updates
Q A late sale at position 3 in an eight-position tree must reach which entries?
Answer: C
An update adds the lowest set bit each time: 3 plus 1 is 4, and 4 plus 4 is 8. Entries 3, 4 and 8 are the blocks that contain position 3.
Checkpoint · The segment tree
Q1/2 In the eight-hour segment tree, hours 0 to 3 are in node 2. A question asks for hours 0 to 3. What happens when it reaches node 2?
Answer: B
A node that lies wholly inside the range gives its total at once. A node that only overlaps asks both children, and a node outside the range gives nothing.
Q2/2 How many nodes does a point update rewrite in a segment tree over n values?
Answer: C
A leaf change alters the total of every ancestor, and there is one ancestor on each level. For 8 hours that is 4 nodes: the leaf, its parent, its grandparent and the root.
Checkpoint · Lazy propagation
Q What does a tag on a segment tree node mean?
Answer: B
A node with a tag has already been given its update, so its own total is right. The children have not seen it yet, and the tag is that debt.
Checkpoint · The sparse table
Q Why may two blocks of a sparse table overlap when you ask for a minimum?
Answer: B
An operation like minimum, maximum or gcd is idempotent: using a value twice gives the same result. A sum is not, so overlapping blocks would count a value twice.
Checkpoint · Choosing
Q1/2 Single hours change often, and managers ask for the minimum takings in a stretch. Which structure fits?
Answer: D
Prefix sums and a Fenwick tree answer totals, and a sparse table cannot take changes cheaply. A segment tree works for any rule you can combine, such as a minimum, and updates one leaf in log n steps.
Q2/2 Whole ranges get a number added, such as "add 5 to hours 2 to 5", and questions ask for totals. Which structure fits?
Answer: C
Updating each hour of the range costs O(n). Tags stop at the few nodes that lie wholly inside the range, so the range update costs O(log n) too.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.