Prefix sum array and difference array
Given an array of numbers, we can construct a new array by replacing each element by the difference between itself and the previous element, except for the first element, which we simply ignore. This is called the difference array, because it contains the first differences of the original array. We will denote the difference array of array by . For example, the difference array of is , or .
We see that the difference array can be computed in linear time from the original array, and is shorter than the original array by one element. Here are implementations in C and Haskell. (Note that the Haskell implementation actually takes a list, but returns an array.)
// D must have enough space for n-1 ints void difference_array(int* A, int n, int* D) { for (int i = 0; i < n-1; i++) D[i] = A[i+1] - A[i]; }
d :: [Int] -> Array Int [Int] d a = listArray (0, length a - 2) (zipWith (-) (tail a) a)
The prefix sum array is the opposite of the difference array. Given an array of numbers and an arbitrary constant , we first append onto the front of the array, and then replace each element with the sum of itself and all the elements preceding it. For example, if we start with , and choose to append the arbitrary value to the front, we obtain , or . Computing the prefix sum array can be done in linear time as well, and the prefix sum array is longer than the original array by one element:
// P must have enough space for n+1 ints void prefix_sum_array(int c, int* A, int n, int* P) { P[0] = c; for (int i = 0; i < n; i++) P[i+1] = P[i] + A[i]; }
p :: Int -> [Int] -> Array Int [Int] p c a = listArray (0, length a) (scanl (+) c a)
Note that every array has an infinite number of possible prefix sum arrays, since we can choose whatever value we want for . For convenience, we usually choose . However, changing the value of has only the effect of shifting all the elements of by a constant. For example, . However, each element of is exactly 23 more than the corresponding element from .
The functions and carry out reverse processes. Given an nonempty zero-indexed array :
- for any . For example, taking the difference array of gives , that is, it restores the original array .
- . Thus, taking and (initial element of ), we have , again restoring the original array .
Contents
Analogy with calculus
These two processes—computing the difference array, and computing a prefix sum array—are the discrete equivalents of differentiation and integration in calculus, which operate on continuous domains. An entry in an array is like the value of a function at a particular point.
- Reverse processes:
- for any . Likewise for any .
- . Likewise .
- Uniqueness:
- A differentiable function can only have one derivative, . An array can only have one difference array, .
- A continuous function has an infinite number of antiderivatives, , where can be any number in its domain, but they differ only by a constant (their graphs are vertical translations of each other). An array has an infinite number of prefix arrays , but they differ only by a constant (at each entry).
- Given some function , and the fact that , an antiderivative of , satisfies , we can uniquely reconstruct . That is, even though has an infinite number of antiderivatives, we can pin it down to one once we are given the value the antiderivative is supposed to attain on the left edge of 's domain. Likewise, given some array and the fact that , a prefix sum array of , satisfies , we can uniquely reconstruct .
- Effect on length:
- is shorter than by one element. Differentiating gives a function (shortens the closed interval to an open interval).
- is longer than by one element. Integrating gives a function (lengthens the open interval to a closed interval).
Because of these similarities, we will speak simply of differentiating and integrating arrays. An array can be differentiated multiple times, but eventually it will shrink to length 0. An array can be integrated any number of times.
Use of prefix sum array
The Fundamental Theorem of Calculus also has an analogue, which is why the prefix sum array is so useful. To compute an integral , which is like a continuous kind of sum of an infinite number of function values , we take any antiderivative , and compute . Likewise, to compute the sum of values , we will take any prefix array and compute . Notice that just as we can use any antiderivative because the constant cancels out, we can use any prefix sum array because the initial value cancels out. (Note our use of the left half-open interval.)
Proof: and . Subtracting gives as desired.
This is best illustrated via example. Let as before. Take . Then, suppose we want . We can compute this by taking . This is because .
When we use the prefix sum array in this case, we generally use for convenience (although we are theoretically free to use any value we wish), and speak of the prefix sum array obtained this way as simply the prefix sum array.
Example: Counting Subsequences (SPOJ)
Computing the prefix sum array is rarely the most difficult part of a problem. Instead, the prefix sum array is kept on hand because the algorithm to solve the problem makes frequent reference to range sums.
We will consider the problem Counting Subsequences from IPSC 2006. Here we are given an array of integers and asked to find the number of contiguous subsequences of the array that sum to 47.
To solve this, we will first transform array into its prefix sum array . Notice that the sum of each contiguous subsequence corresponds to the difference of two elements of , that is, . So what we want to find is the number of pairs with and . (Note that if , we will instead get a subsequence with sum -47.)
However, this is quite easy to do. We sweep through from left to right, keeping a map of all elements of we've seen so far, along with their frequencies; and for each element we count the number of times has appeared so far, by looking up that value in our map; this tells us how many contiguous subsequences ending at have sum 47. And finally, adding the number of contiguous subsequences with sum 47 ending at each entry of gives the total number of such subsequences in the array. Total time taken is , if we use a hash table implementation of the map.
Use of difference array
The difference array is used to keep track of an array when ranges of said array can be updated all at once. If we have array and add an increment to elements , then notice that are not affected; that is increased by ; that are not affected; that is decreased by ; and that are unaffected. Thus, if we are required to update many ranges of an array in this manner, we should keep track of rather than itself, and then integrate at the end to reconstruct .
Example: Wireless (CCC)
This is the basis of the model solution to Wireless from CCC 2009. We are given a grid of lattice points with up to 30000 rows and up to 1000 columns, and up to 1000 circles, each of which is centered at a lattice point. Each circle has a particular weight associated with it. We want to stand at a lattice point such that the sum of the weights of all the circles covering it is maximized, and to determine how many such lattice points there are.
The most straightforward way to do this is by actually computing the sum of weights of all covering circles at each individual lattice point. However, doing this naively would take up to operations, as we would have to consider each lattice point and each circle and decide whether that circle covers that lattice point.
To solve this, we will treat each column of the lattice as an array , where entry denotes the sum of weights of all the circles covering the point in row of that column. Now, consider any of the given circles. Either this circle does not cover any points in this column at all, or the points it covers in this column will all be consecutive. (This is equivalent to saying that the intersection of a circle with a line is a line segment.) For example, a circle centered at with radius will cover no lattice points with x-coordinate , and as for lattice points with x-coordinate , it will cover . Thus, the circle covers some first point and some last point , and adds some value to each point that it covers; that is, it adds to . Thus, we will simply maintain the difference array , noting that the circle adds to and takes away from . We maintain such a difference array for each column; and we perform at most two updates for each circle-column pair; so the total number of updates is bounded by . (The detail of how to keep track of the initial element of is left as an exercise to the reader.) After this, we perform integration on each column and find the maximum values, which requires at most a constant times the total number of lattice points, which is up to .
Multiple dimensions
The prefix sum array and difference array can be extended to multiple dimensions.
Prefix sum array
We start by considering the two-dimensional case. Given an array , we will define the prefix sum array as follows: . In other words, the first row of is all zeroes, the first column of is all zeroes, and all other elements of are obtained by adding up some upper-left rectangle of values of . For example, . Or, more easily expressed, is the sum of all entries of with indices in (Cartesian product).
In general, if we are given an -dimensional array with dimensions , then the prefix sum array has dimensions , and is defined by ; or we can simply say that it is the sum of all entries of with indices in .
To compute the prefix sum array in the two-dimensional case, we will scan first down and then right, as suggested by the following C++ implementation:
vector<vector<int> > P(vector<vector<int> > A) { int m = A.size(); int n = A[0].size(); // Make an m+1 by n+1 array and initialize it with zeroes. vector<vector<int> > p(m+1, vector<int>(n+1, 0)); for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) p[i][j] = p[i-1][j] + A[i-1][j-1]; for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) p[i][j] += p[i][j-1]; return p; }
Here, we first make each column of the prefix sum array of a column of , then convert each row of into its prefix sum array to obtain the final values. That is, after the first pair of for loops, will be equal to , and after the second pair, we will then have , as desired. The extension of this to more than two dimensions is straightforward.
(Haskell code is not shown, because using functional programming in this case does not make the code nicer.)
After the prefix sum array has been computed, we can use it to add together any rectangle in , that is, all the elements with their indices in . To do so, we first observe that gives the sum of all the elements with indices in the box . Then we similarly observe that corresponds to the box . Subtracting gives the box . This gives a final formula of .
In the -dimensional case, to sum the elements of with indices in the box , we will use the formula . We will not state the proof, instead noting that it is a form of the inclusion–exclusion principle.
Example: Diamonds (BOI)
The problem Diamonds from BOI '09 is a straightforward application of the prefix sum array in three dimensions. We read in a three-dimensional array , and then compute its prefix sum array; after doing this, we will be able to determine the sum of any box of the array with indices in the box as .
Difference array
To use the difference array properly in two dimensions, it is easiest to use a source array with the property that the first row and first column consist entirely of zeroes. (In multiple dimensions, we will want whenever any of the 's are zero.)
We will simply define the difference array to be the array whose prefix sum array is . This means in particular that is the sum of elements of with indices in the box (this box contains only the single element ). Using the prefix sum array , we obtain . In general:
- .
Should we actually need to compute the difference array, on the other hand, the easiest way to do so is by reversing the computation of the prefix sum array:
vector<vector<int> > D(vector<vector<int> > A) { int m = A.size(); int n = A[0].size(); // Make an m+1 by n+1 array vector<vector<int> > d(m-1, vector<int>(n-1)); for (int i = 0; i < m-1; i++) for (int j = 0; j < n-1; j++) d[i][j] = A[i+1][j+1] - A[i+1][j]; for (int i = m-2; i > 0; i--) for (int j = 0; j < n-1; j++) d[i][j] -= d[i-1][j]; return d; }
In this code, we first make each column of the difference array of the corresponding column of , and then treat each row as now being the prefix sum array of the final result (the row of the difference array), so we scan backward through it to reconstruct the original array (i.e., take the difference array of the row). (We have to do this backward so that we won't overwrite a value we still need later.) The extension to multiple dimensions is straightforward; we simply have to walk backward over every additional dimension as well.
Now we consider what happens when all elements of with coordinates in the box given by are incremented by . If we take the difference array of each column of now, as in the function D
defined above, we see that for each column, we will have to add to entry and subtract it from (as in the one-dimensional case). Now if we take the difference array of each row of what we've just obtained, we notice that in row number , we've added to every element in columns in in the previous step, and in row number , we've subtracted to every element in the same column range, so in the end the effect is to add to elements and , and to subtract from elements and .
In the general case, when adding to all elements of with indices in the box , a total of elements of need to be updated. In particular, element (where each of the 's can be either 0 or 1, giving possibilities in total) is incremented by . That is, if we consider an -dimensional array to be an -dimensional hypercube of numbers, then the elements to be updated lie on the corners of an -dimensional hypercube; we 2-color the vertices black and white (meaning two adjacent vertices always have opposite colours), with the lowest corner (corresponding to indices ) white; and each white vertex receiving and each black vertex . One can attempt to visualize the effect this has on the prefix sum array in three dimensions, and become convinced that it makes sense in dimensions. Each element in the prefix sum array is the sum of all the elements in some box of the difference array with its lowest corner at the origin, . If the highest corner actually lies within the hypercube, that is, , then this box is only going to contain the low corner , which has increased by ; thus, this entry in has increased by as well, and this is true of all elements that lie within the hypercube, . If any of the 's are less than the lower bound of the corresponding , then our box doesn't hit any of the vertices of the hypercube at all, so all these elements are unaffected; and if instead any one of them goes over the upper bound, then our box passes in through one hyperface and out through another, which means that corresponding vertices on the low and high face will either both be hit or both not be hit, and each pair cancels itself out, giving again no change outside the hypercube.
Example: The Cake is a Dessert
The Cake is a Dessert from the Waterloo–Woburn 2011 Mock CCC is a straightforward application of the difference array in two dimensions.
A word on the dynamic case
The dynamic version of the problem that the prefix sum array is intended to solve requires us to be able to carry out an intermixed sequence of operations, where each operation either changes an element of or asks us to determine the sum for some . That is, we need to be able to compute entries of the prefix sum array of an array that is changing (dynamic). If we can do this, then we can do range sum queries easily on a dynamic array, simply by taking the difference of prefix sums as in the static case. This is a bit trickier to do, but is most easily and efficiently accomplished using the binary indexed tree data structure, which is specifically designed to solve this problem and can be updated in time, where is the number of dimensions and each is a dimension. Each prefix sum query also takes that amount of time, but we need to perform of these to find a box sum using the formula given previously, so the running time of the query is asymptotically times greater than that of the update. In the most commonly encountered one-dimensional case, both query and update are simply .
The dynamic version of the problem that the difference array is intended to solve is analogous: we want to be able to increment entire ranges of an array, but at any point we also want to be able to determine any element of the array. Here, we simply use a binary indexed tree for the difference array, and compute prefix sums whenever we want to access an element. Here, it is the update that is slower by a factor of than the query (because we have to update entries at a time, but only query one.)
On the other hand, if we combine the two, that is, we wish to be able to increment ranges of some array as well as query prefix sums of in an intermixed sequence, matters become more complicated. Notice that in the static case we would just track the difference array of and then integrate twice at the end. In the dynamic case, however, we need to use a segment tree with lazy propagation. This will give us time on both the query and the update, but is somewhat more complex and slower than the binary indexed tree on the invisible constant factor.