Find the suffix factorials of a suffix sum array of the given array
Given an array arr[] consisting of N positive integers, the task is to find the suffix factorials of a suffix sum array of the given array.
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: {3628800, 362880, 5040, 24}
Explanation: The suffix sum of the given array is {10, 9, 7, 4}.
Therefore, suffix factorials of the obtained suffix sum array is {10!, 9!, 7!, 4!}Input: arr[] = {2, 0}
Output: {2, 1}
Approach: The task can be solved by pre-calculating the factorials of all numbers till the entire sum of the array. So that the factorial calculation at each index of the suffix sum array is can be calculated in unit time.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the factorial of// suffix sum at every possible indexvoid suffixFactorialArray(int A[], int N){ // Find the suffix sum array for (int i = N - 2; i >= 0; i--) { A[i] += A[i + 1]; } // Stores the factorial of all the // element till the sum of array int fact[A[0] + 1]; fact[0] = 1; // Find the factorial array for (int i = 1; i <= A[0]; i++) { fact[i] = i * fact[i - 1]; } // Find the factorials of // each array element for (int i = 0; i < N; i++) { A[i] = fact[A[i]]; } // Print the resultant array for (int i = 0; i < N; i++) { cout << A[i] << " "; }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); suffixFactorialArray(arr, N); return 0;} |
3628800 362880 5040 24
Time Complexity: O(N + M), where M is the sum of array elements.
Auxiliary Space: O(M)


.png)