As commented by Yves Daoust, seems like a suffix sum array with additional zero-element (as sum over empty array).
Suffix Sum
Some notes on Suffix Sum:
Given an array ‘A’ of size N, its suffix sum array is an array of the same size N such that the ith element of the suffix sum array ‘Suffix’ is the sum of all elements of the given array till ith index from the end, i.e Suffix[i] = A[i] + A[i+1] + A[i+2] + … + A[N-1] - (0-Based indexing).
For Example:
Given A[] = [3, 4, -1, 2, 5], the suffix sum array S[] is given as - S[0] = 13, S1 = 10, S1 = 6, S3 = 7, S[5] = 5.
i.e. S[] = [13, 10, 6, 7, 5]
See also:
- Dev.to (2020): Prefix Sum & Suffix Sum - Programming Tools
- Wikipedia: suffix array (might be related, not sure)
Implementation
Following approach uses these concepts for performance:
- predefined, fix-sized result array (instead of extending or list-comprehension)
- fix-sized loop
for i
(instead of recursion) to reverse increment
- explicit fast-returning if-branch for inputs with 0 or 1 elements
def suffix_sum(arr):
result = arr + [0] # add the zero as last element for this task (copied input)
n = len(arr)
if (n <= 1): # input with 0 or 1 elements returned as is
return result
last = n-1 # the last of the input array stays unmodified
# iterate by element (last to first):
for i in range(last, -1, -1): # step backwards from last to first
result[i] = result[i+1] + arr[i] # result-sum = previous-sum + element (increases with each element)
return result
Results for 3 test-cases:
in: [0, 1, 3, 6, 10]
out:[20, 20, 19, 16, 10, 0]
in: []
out:[0]
in: [1234]
out:[1234, 0]
Notes:
Debug-print each iteration with print(f"{i:2}: {result[i]} = {result[i+1]} + {arr[i]}")
shows 4 iterations for example-input [0, 1, 3, 6, 10]
with length n=5
:
3: 16 = 10 + 6
2: 19 = 16 + 3
1: 20 = 19 + 1
0: 20 = 20 + 0