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, not an array, and will work fine for infinite lists.)
// 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] -> [Int] -- NB: The general type signature should be (Num a) => [a] -> [a] d a = 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] -> [Int] -- NB: The general type signature should be (Num a) => a -> [a] -> [a] p = scanl (+) -- NB: This is the same as p c 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 .
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 .
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.