Data Structures19 sections · 729 units
Open in Course

Building Block Sums

Preprocessing

Start with range sum queries. Precompute the sum of each block in O(n)O(n) time. For each element at index ii, add it to blockSum[i/B]blockSum[\lfloor i/B \rfloor].

After processing all elements, blockSum[k]blockSum[k] holds the sum of block kk. This preprocessing happens once.

Now queries can skip entire blocks by using precomputed sums instead of iterating through every element. The space is O(n)O(\sqrt{n}) for the block sums array.