update method

void update(
  1. int index,
  2. num value
)

Sets the element at index (0-based) to value, in O(log n). Requires 0 <= index < length.

Example:

final SegmentTree t = SegmentTree.sum(<num>[1, 2, 3]);
t.update(1, 10);
t.query(0, 2); // 14

Audited: 2026-06-12 11:26 EDT

Implementation

void update(int index, num value) {
  // Enforced in release (an assert strips): a negative index in [-_n, 0) maps
  // to a valid array slot `index + _n` and would silently update the wrong
  // leaf, corrupting every ancestor — not a throw.
  if (index < 0 || index >= _n) {
    throw RangeError.range(index, 0, _n - 1, 'index');
  }
  int pos = index + _n;
  _tree[pos] = value;
  // Recompute every ancestor by re-combining its two children.
  for (pos >>= 1; pos >= 1; pos >>= 1) {
    _tree[pos] = _combine(_tree[pos * 2], _tree[pos * 2 + 1]);
  }
}