Product Array Puzzle

Posted: 22 Dec, 2020
Difficulty: Easy


Try Problem

You are given an array of ‘N’ integers. You need to return another array ‘product’ such that ‘product[i]’ contains the product of all the arrays except the element at the ith position in the given array.

As the product of elements can be very large you need to return the answer in mod (10^9+7).
Follow Up
Try to do this without using the division operator ‘/’, in constant space. The output array does not count as extra space for the purpose of space complexity analysis.
Input Format:
The first line of the input contains an integer ‘T’ denoting the number of test cases.

The first line of each test case contains a single positive integer ‘N’ denoting the number of the elements present in the array.

The second line of each test case contains ‘N’ space-separated integers denoting the elements of the array.
Output Format:
The only line of output of each test case should contain ‘N’ space-separated integers where ith integer denotes the product of all the elements in the array except itself.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10^2
2 <= N<= 10^4
1 <= A[i] <= 10^9 

Where ‘T’ is the number of test cases, ‘N’ is the size of the array,  ‘A[i]’ is the size of the array elements.

Time Limit: 1 sec
Approach 1
  1. For each element, we need to find the product of all elements except the current element in the given array. We will create a ‘product’ array for storing the answer for each element.
  2. For each element, we run a loop and store the product of all elements in the array but as soon as we reach the index of the current element we should not include this in our product.
  3. After the loop is over we set the value of product[i] to the calculated product.
  4. Finally, after filling each position in ‘product’ we will return this array.
Try Problem