prefixSum method

num prefixSum(
  1. int index
)

Sum of elements [0..index] inclusive (0-based), in O(log n). Requires 0 <= index < length. Audited: 2026-06-12 11:26 EDT

Implementation

num prefixSum(int index) {
  // Throw in release: an out-of-range index otherwise reads a stale partial
  // sum (high) or a wrong walk (negative), returning a silently bad total.
  if (index < 0 || index >= _size) {
    throw RangeError('index ($index) out of range [0, $_size)');
  }
  num sum = 0;
  // Walk toward the root by stripping the lowest set bit each step.
  for (int i = index + 1; i > 0; i -= i & -i) {
    sum += _tree[i];
  }
  return sum;
}