Multiple dimensions
This time, we have an analogue of the first problem — but on a grid of size , as subrectangle queries. The naive solution would take time, which is obviously too slow. The first obvious optimization would be to instead create a prefix sum array for each row, resulting in operations. This might be enough to pass for and as in the problem above, but we want an even faster solution.
Similar to what we did for the 1D version, we will build a “prefix matrix” , where is the sum of the subrectangle bounded by the cells and . To calculate this matrix, notice how we can sum and , and then subtract as it was counted twice. Finally, we have to add .
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
Using this prefix matrix is similar to building it. Assume we wish to query the subrectangle . After adding and subtracting both and has been subtracted twice, so we add it once more. This gives us the formula
It is simple to generalize this further to dimensions using the Inclusion-Exclusion Principle.