Prefix and Range Sums with a Fenwick Tree
Keep prefix and range sums up to date while numbers change, using a Fenwick tree.
The problem
Implement fenwick_tree_trace(values, operations). values is a list of integers. Each operation is one of: ["prefix", index], which asks for values[0] + ... + values[index]; ["add", index, delta], which adds delta to the number at position index; or ["range", left, right], which asks for values[left] + ... + values[right]. All indexes are 0-based and both ends of a range are included. Run the operations in order and return the answers to the "prefix" and "range" operations as a list. Do not change the input list. Use a Fenwick tree (binary indexed tree) so each operation takes O(log n) time.
Starter code
def fenwick_tree_trace(values, operations):
passPublic examples
values = [2, 1, 5, 3], operations = [["prefix", 2], ["add", 1, 4], ["range", 1, 3]]gives[8, 13]values = [4, 6], operations = [["range", 0, 0], ["prefix", 1]]gives[4, 10]
Solving it in the practice book needs an active paid plan.
Open it in the practice bookOne thought at a time.
