# A product array puzzle (O(1) Space) in C++?

C++Server Side ProgrammingProgramming

Here we will see one interesting problem related to array. There is an array with n elements. We have to create another array of n elements. But the i-th position of second array will hold the product of all elements of the first array except the i-th element. And one constraint is that we cannot use the division operator in this problem. We have to solve this problem in-place without using any additional spaces.

If we can use the division, operation, we can easily solve this problem, by getting the product of all elements, then divide i-th element of first array and store it into i-th place of the second array.

Here we are solving by taking one temp variable, that is finding the product of left part and the right part. This value will be placed into the final array. So it will not take extra space.

## Algorithm

### productArray(arr, n)

begin
define an array called res of size n
fill the res array with 1
temp := 1
for i in range 1 to n, do
res[i] := temp;
temp := temp * arr[i]
done
for i in range n-1 down to 0, do
res[i] = res[i] * temp
temp := temp * arr[i]
done
return res
end

## Example

Live Demo

#include<iostream>
using namespace std;
void printArray(int arr[], int n) {
for(int i = 0; i<n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void productArray(int arr[], int product[], int n) {
int temp = 1;
for(int i = 0; i<n; i++) {
product[i] = 1; //set all elements of product as 1
}
for(int i = 0; i < n; i++) { //temp variable will hold product of elements on left excluding arr[i]
product[i] = temp;
temp *= arr[i];
}
temp = 1;
for(int i = n - 1; i >= 0; i--) { //temp variable will hold product of elements on right excluding arr[i]
product[i] *= temp;
temp *= arr[i];}
}
}
main() {
int myArr[7] = {5, 4, 7, 6, 9, 2, 3};
int resArr[7];
cout << "Initial Array: ";
printArray(myArr, 7);
productArray(myArr, resArr, 7);
cout << "Final Array: ";
printArray(resArr, 7);
}

## Output

Initial Array: 5 4 7 6 9 2 3
Final Array: 9072 11340 6480 7560 5040 22680 15120
Published on 24-Jul-2019 12:19:34