Build prefix sums for . Let (empty prefix). , , , , , .
Now answer: sum of (0-indexed)? That's . Check: . Correct! Each query is after preprocessing. For queries, this beats the naive approach.
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
Tracing the algorithm
Build prefix sums for . Let (empty prefix). , , , , , .
Now answer: sum of (0-indexed)? That's . Check: . Correct! Each query is after preprocessing. For queries, this beats the naive approach.