AlgoScope

Range Sum Query

The sum of a range is the total up to its end minus the total before its start.

Array algorithms and techniques, algorithm, beginner
The range sum is prefix at 5 minus prefix at 1.active 2-530418293144235256317
The range sum is prefix at 5 minus prefix at 1.active 2-530418293144235256317

Prefix Sum and Kadane: Range sum from prefix totals

Step, step 10 of 11

Sum of 2 to 5 is prefix[5] minus prefix[1]: everything up to 5, less everything before 2.

Cost

Best
O(1)
Average
O(1)
Worst
O(1)
Space
O(n)

After O(n) preprocessing.

Taught by the same lesson

Prefix Sum and Kadane covers these too, in the same run.