Data Structures19 sections · 729 units
Open in Course

Range Sum Query

Combining blocks

To answer sum(l,r)sum(l, r), split the range into three parts:

1.1. Left tail: elements from ll to the end of ll's block

2.2. Complete blocks: all blocks fully contained in [l,r][l, r]

3.3. Right tail: elements from the start of rr's block to rr For the tails, iterate through individual elements. For complete blocks, add precomputed sums. If ll and rr are in the same block, just iterate from ll to rr directly. Time: O(n)O(\sqrt{n}). The tails have at most BB elements each, and there are at most n/Bn/B complete blocks. Both terms are O(n)O(\sqrt{n}).