![]() |
VOOZH | about |
Suffix Sum ArrayGiven an array arr[] of size N, the task is to compute and return its suffix sum array.
Suffix Sum is a precomputation technique in which the sum of all the elements of the original array from an index i till the end of the array is computed.
Therefore, this suffix sum array will be created using the relation:
Examples:
Input: arr[] = { 15, 10, 25, 5, 10, 20 } , N = 6
Output: suffixSum[] = { 85, 70, 60, 35, 30, 20}
Explanation: While traversing the array from back, keep adding element from the back with element at current index.
suffixSum[5] = 20,
suffixSum[4] =suffixSum[5] + arr[4] = 20+10 = 30 ,
suffixSum[3] = suffixSum[4] + arr[3] = 30+5 = 35 and so on.Input: arr[] = {10, 14, 16, 20}, n = 6
Output: suffixSum[] = {60, 50, 36, 20}
Explanation: suffixSum[3] = 20,
suffixSum[2] =suffixSum[3] + arr[2] = 20+16 = 36 ,
suffixSum[1] = suffixSum[2] + arr[1] = 36+14 = 40 and so on.
Naive Approach:
The naive approach to solve the problem is to traverse each element of the array and for each element calculate the sum of remaining elements to its right including itself using another loop.
Algorithm:
Below is the implementation of the approach:
Suffix sum array: 60 50 36 20
Time Complexity: O(n*n) where n is size of input array. This is because two nested loops are executing.
Auxiliary Space: O(N), to store the suffix sum array.
Approach: To fill the suffix sum array, we run through index N-1 to 0 and keep on adding the current element with the previous value in the suffix sum array.
Below is the implementation of the above approach to create a suffix sum array:
Suffix sum array: 60 50 36 20
Time Complexity: O(N), to traverse the original array for computing suffix sum.
Auxiliary Space: O(N), to store the suffix sum array.