The Wayback Machine - https://web.archive.org/web/20220204033243/https://www.geeksforgeeks.org/find-the-suffix-factorials-of-a-suffix-sum-array-of-the-given-array/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find the suffix factorials of a suffix sum array of the given array

  • Last Updated : 03 Feb, 2022

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 index
void 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 Code
int main()
{
    int arr[] = { 1, 2, 3, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    suffixFactorialArray(arr, N);
    return 0;
}
Output
3628800 362880 5040 24 

Time Complexity: O(N + M), where M is the sum of array elements.
Auxiliary Space: O(M)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!