Skip to contentKEEP THE CRAFTTHE SANCTUARY

Maintain Segment-Tree Range Sums

Answer inclusive range sums while single values change, using a segment tree stored in one array.

The problem

Implement segment_tree_ranges(values, operations). values is a non-empty list of integers. Each operation is either ["sum", left, right], which asks for values[left] + ... + values[right] with both ends included, or ["update", index, value], which sets the number at position index to value. Run the operations in order and return the answers to the "sum" operations as a list. Do not change the input list. Use a segment tree so that every operation takes O(log n) time.

Starter code

def segment_tree_ranges(values, operations):
    pass

Public examples

  1. values = [2, 1, 5, 3], operations = [["sum", 1, 3], ["update", 2, 4], ["sum", 0, 2]]gives[9, 7]
  2. values = [8], operations = [["sum", 0, 0], ["update", 0, -2], ["sum", 0, 0]]gives[8, -2]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.