Given an array arr[] consisting of N positive integers, the task is to find the prefix factorials of a prefix sum array of the given array i.e., .
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: 1 6 720 3628800
Explanation:
The prefix sum of the given array is {1, 3, 6, 10}. Therefore, prefix factorials of the obtained prefix sum array is {1!, (1+2)!, (1+2+3)!, (1+2+3+4)!} = {1!, 3!, 6!, 10!} = {1 6 720 3628800}.Input: arr[] = {2, 4, 3, 1}
Output: 2 720 362880 3628800
Naive Approach: The simplest approach to solve the given problem is to find the prefix sum of the given array and then find the factorial of each array element in the prefix sum array. After calculating the prefix sum print the factorial array.
Below is the implementation of the above approach.
C++
|
1 6 720 3628800
Time Complexity: O(N*M), where M is the sum of the array elements.
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized by precalculating the factorial of sum of the array elements so that the factorial calculation at each index is can be calculated in O(1) time.
Below is an implementation of the above approach:
C++
|
1 6 720 3628800
Time Complexity: O(N + M), where M is the sum of the array elements.
Auxiliary Space: O(M), where M is the sum of the array elements.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Original page link
Best Cool Tech Gadgets
Top favorite technology gadgets
0 comments:
Post a Comment