VOOZH about

URL: https://www.geeksforgeeks.org/dsa/prefix-product-array/

⇱ Prefix Product Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Prefix Product Array

Last Updated : 26 Mar, 2021

Given an array arr[] of N integers the task is to generate a prefix product array from the given array.
 

In a prefix product array, ith term pref[i] = arr[i] * arr[i - 1] * ...... * arr[0] 
 


Examples: 
 

Input: {1, 2, 3, 4, 5} 
Output: {1, 2, 6, 24, 120} 
Explanation: 
The Prefix Product Array will be {1, 2*1, 3*2*1, 4*3*2*1, 5*4*3*2*1} = {1, 2, 6, 24, 120}
Input: {2, 4, 6, 5, 10} 
Output: {2, 8, 48, 240, 2400} 
 


 


Approach: 
Follow the steps below to solve the problem: 
 

  • Iterate over the given array from indices 1 to N - 1
     
  • Calculate arr[i] = arr[i] * arr[i-1] for every ith index. 
     
  • Finally, print the prefix product array. 
     


Below is the implementation of the above approach.
 


Output: 
2, 8, 48, 240, 2400

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 

Comment
Article Tags: