 Open in App
Not now

# Product of Array except itself

• Difficulty Level : Medium
• Last Updated : 15 Feb, 2023

Given an array arr[] of n integers, construct a Product Array prod[] (of the same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i].

Note: Solve it without the division operator in O(n) time.

Example :

```Input: arr[]  = {10, 3, 5, 6, 2}
Output: prod[]  = {180, 600, 360, 300, 900}
3 * 5 * 6 * 2 product of other array
elements except 10 is 180
10 * 5 * 6 * 2 product of other array
elements except 3 is 600
10 * 3 * 6 * 2 product of other array
elements except 5 is 360
10 * 3 * 5 * 2 product of other array
elements except 6 is 300
10 * 3 * 6 * 5 product of other array
elements except 2 is 900

Input: arr[]  = {1, 2, 3, 4, 5}
Output: prod[]  = {120, 60, 40, 30, 24 }
2 * 3 * 4 * 5  product of other array
elements except 1 is 120
1 * 3 * 4 * 5  product of other array
elements except 2 is 60
1 * 2 * 4 * 5  product of other array
elements except 3 is 40
1 * 2 * 3 * 5  product of other array
elements except 4 is 30
1 * 2 * 3 * 4  product of other array
elements except 5 is 24```
Recommended Practice

A naive approach: Store the product of all the elements is variable and then iterate the array and add product/current_index_value in a new array. and then return this new array. But as per the problem statement this is not a valid approach:

An approach using prefix and suffix multiplication: Create two extra space, i.e. two extra arrays to store the product of all the array elements from start, up to that index and another array to store the product of all the array elements from the end of the array to that index.
To get the product excluding that index, multiply the prefix product up to index i-1 with the suffix product up to index i+1.

Algorithm:

1. Create two array prefix and suffix of length n, i.e length of the original array, initialize prefix = 1 and suffix[n-1] = 1 and also another array to store the product.
2. Traverse the array from second index to end.
3. For every index i update prefix[i] as prefix[i] = prefix[i-1] * array[i-1], i.e store the product upto i-1 index from the start of array.
4. Traverse the array from second last index to start.
5. For every index i update suffix[i] as suffix[i] = suffix[i+1] * array[i+1], i.e store the product upto i+1 index from the end of array
6. Traverse the array from start to end.
7. For every index i the output will be prefix[i] * suffix[i], the product of the array element except that element.

## C++

 `// C++ implementation of above approach` `#include ` `using` `namespace` `std;`   `/* Function to print product array` `for a given array arr[] of size n */` `void` `productArray(``int` `arr[], ``int` `n)` `{`   `    ``// Base case` `    ``if` `(n == 1) {` `        ``cout << 0;` `        ``return``;` `    ``}` `    ``/* Allocate memory for temporary` `arrays left[] and right[] */` `    ``int``* left = ``new` `int``[``sizeof``(``int``) * n];` `    ``int``* right = ``new` `int``[``sizeof``(``int``) * n];`   `    ``/* Allocate memory for the product array */` `    ``int``* prod = ``new` `int``[``sizeof``(``int``) * n];`   `    ``int` `i, j;`   `    ``/* Left most element of left` `array is always 1 */` `    ``left = 1;`   `    ``/* Right most element of right` `array is always 1 */` `    ``right[n - 1] = 1;`   `    ``/* Construct the left array */` `    ``for` `(i = 1; i < n; i++)` `        ``left[i] = arr[i - 1] * left[i - 1];`   `    ``/* Construct the right array */` `    ``for` `(j = n - 2; j >= 0; j--)` `        ``right[j] = arr[j + 1] * right[j + 1];`   `    ``/* Construct the product array using` `        ``left[] and right[] */` `    ``for` `(i = 0; i < n; i++)` `        ``prod[i] = left[i] * right[i];`   `    ``/* print the constructed prod array */` `    ``for` `(i = 0; i < n; i++)` `        ``cout << prod[i] << ``" "``;`   `    ``return``;` `}`   `/* Driver code*/` `int` `main()` `{` `    ``int` `arr[] = { 10, 3, 5, 6, 2 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``cout << ``"The product array is: \n"``;` `    ``productArray(arr, n);` `}`   `// This is code is contributed by rathbhupendra`

## C

 `#include ` `#include `   `/* Function to print product array` `for a given array arr[] of size n */` `void` `productArray(``int` `arr[], ``int` `n)` `{`   `    ``// Base case` `    ``if` `(n == 1) {` `        ``printf``(``"0"``);` `        ``return``;` `    ``}`   `    ``/* Allocate memory for temporary` `arrays left[] and right[] */` `    ``int``* left = (``int``*)``malloc``(``sizeof``(``int``) * n);` `    ``int``* right = (``int``*)``malloc``(``sizeof``(``int``) * n);`   `    ``/* Allocate memory for the product array */` `    ``int``* prod = (``int``*)``malloc``(``sizeof``(``int``) * n);`   `    ``int` `i, j;`   `    ``/* Left most element of left array` `is always 1 */` `    ``left = 1;`   `    ``/* Right most element of right` `array is always 1 */` `    ``right[n - 1] = 1;`   `    ``/* Construct the left array */` `    ``for` `(i = 1; i < n; i++)` `        ``left[i] = arr[i - 1] * left[i - 1];`   `    ``/* Construct the right array */` `    ``for` `(j = n - 2; j >= 0; j--)` `        ``right[j] = arr[j + 1] * right[j + 1];`   `    ``/* Construct the product array using` `    ``left[] and right[] */` `    ``for` `(i = 0; i < n; i++)` `        ``prod[i] = left[i] * right[i];`   `    ``/* print the constructed prod array */` `    ``for` `(i = 0; i < n; i++)` `        ``printf``(``"%d "``, prod[i]);`   `    ``return``;` `}`   `/* Driver program to test above functions */` `int` `main()` `{` `    ``int` `arr[] = { 10, 3, 5, 6, 2 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``printf``(``"The product array is: \n"``);` `    ``productArray(arr, n);` `    ``getchar``();` `}`

## Java

 `class` `ProductArray {` `    ``/* Function to print product array` `    ``for a given array arr[] of size n */` `    ``void` `productArray(``int` `arr[], ``int` `n)` `    ``{`   `        ``// Base case` `        ``if` `(n == ``1``) {` `            ``System.out.print(``0``);` `            ``return``;` `        ``}` `        ``// Initialize memory to all arrays` `        ``int` `left[] = ``new` `int``[n];` `        ``int` `right[] = ``new` `int``[n];` `        ``int` `prod[] = ``new` `int``[n];`   `        ``int` `i, j;`   `        ``/* Left most element of left array` `is always 1 */` `        ``left[``0``] = ``1``;`   `        ``/* Right most element of right` `array is always 1 */` `        ``right[n - ``1``] = ``1``;`   `        ``/* Construct the left array */` `        ``for` `(i = ``1``; i < n; i++)` `            ``left[i] = arr[i - ``1``] * left[i - ``1``];`   `        ``/* Construct the right array */` `        ``for` `(j = n - ``2``; j >= ``0``; j--)` `            ``right[j] = arr[j + ``1``] * right[j + ``1``];`   `        ``/* Construct the product array using` `        ``left[] and right[] */` `        ``for` `(i = ``0``; i < n; i++)` `            ``prod[i] = left[i] * right[i];`   `        ``/* print the constructed prod array */` `        ``for` `(i = ``0``; i < n; i++)` `            ``System.out.print(prod[i] + ``" "``);`   `        ``return``;` `    ``}`   `    ``/* Driver program to test the above function */` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``ProductArray pa = ``new` `ProductArray();` `        ``int` `arr[] = { ``10``, ``3``, ``5``, ``6``, ``2` `};` `        ``int` `n = arr.length;` `        ``System.out.println(``"The product array is : "``);` `        ``pa.productArray(arr, n);` `    ``}` `}`   `// This code has been contributed by Mayank Jaiswal`

## Python3

 `# Python implementation of the above approach`   `# Function to print product array for a given array` `# arr[] of size n`     `def` `productArray(arr, n):`   `    ``# Base case` `    ``if``(n ``=``=` `1``):` `        ``print``(``0``)` `        ``return`   `    ``# Allocate memory for temporary arrays left[] and right[]` `    ``left ``=` `[``0``]``*``n` `    ``right ``=` `[``0``]``*``n`   `    ``# Allocate memory for the product array` `    ``prod ``=` `[``0``]``*``n`   `    ``# Left most element of left array is always 1` `    ``left[``0``] ``=` `1`   `    ``# Right most element of right array is always 1` `    ``right[n ``-` `1``] ``=` `1`   `    ``# Construct the left array` `    ``for` `i ``in` `range``(``1``, n):` `        ``left[i] ``=` `arr[i ``-` `1``] ``*` `left[i ``-` `1``]`   `    ``# Construct the right array` `    ``for` `j ``in` `range``(n``-``2``, ``-``1``, ``-``1``):` `        ``right[j] ``=` `arr[j ``+` `1``] ``*` `right[j ``+` `1``]`   `    ``# Construct the product array using` `    ``# left[] and right[]` `    ``for` `i ``in` `range``(n):` `        ``prod[i] ``=` `left[i] ``*` `right[i]`   `    ``# print the constructed prod array` `    ``for` `i ``in` `range``(n):` `        ``print``(prod[i], end``=``' '``)`     `# Driver code` `arr ``=` `[``10``, ``3``, ``5``, ``6``, ``2``]` `n ``=` `len``(arr)` `print``(``"The product array is:"``)` `productArray(arr, n)`   `# This code is contributed by ankush_953`

## C#

 `using` `System;`   `class` `GFG {`   `    ``/* Function to print product array` `    ``for a given array arr[] of size n */` `    ``static` `void` `productArray(``int``[] arr, ``int` `n)` `    ``{`   `        ``// Base case` `        ``if` `(n == 1) {` `            ``Console.Write(0);` `            ``return``;` `        ``}` `        ``// Initialize memory to all arrays` `        ``int``[] left = ``new` `int``[n];` `        ``int``[] right = ``new` `int``[n];` `        ``int``[] prod = ``new` `int``[n];`   `        ``int` `i, j;`   `        ``/* Left most element of left array` `        ``is always 1 */` `        ``left = 1;`   `        ``/* Right most element of right` `        ``array is always 1 */` `        ``right[n - 1] = 1;`   `        ``/* Construct the left array */` `        ``for` `(i = 1; i < n; i++)` `            ``left[i] = arr[i - 1] * left[i - 1];`   `        ``/* Construct the right array */` `        ``for` `(j = n - 2; j >= 0; j--)` `            ``right[j] = arr[j + 1] * right[j + 1];`   `        ``/* Construct the product array using` `        ``left[] and right[] */` `        ``for` `(i = 0; i < n; i++)` `            ``prod[i] = left[i] * right[i];`   `        ``/* print the constructed prod array */` `        ``for` `(i = 0; i < n; i++)` `            ``Console.Write(prod[i] + ``" "``);`   `        ``return``;` `    ``}`   `    ``/* Driver program to test the above function */` `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = { 10, 3, 5, 6, 2 };` `        ``int` `n = arr.Length;` `        ``Console.Write(``"The product array is :\n"``);`   `        ``productArray(arr, n);` `    ``}` `}`   `// This code is contributed by nitin mittal.`

## PHP

 `= 0; ``\$j``--) ` `        ``\$right``[``\$j``] = ``\$arr``[``\$j` `+ 1] * ` `                    ``\$right``[``\$j` `+ 1]; `   `    ``// Construct the product array ` `    ``// using left[] and right[] ` `    ``for` `(``\$i` `= 0; ``\$i` `< ``\$n``; ``\$i``++) ` `        ``\$prod``[``\$i``] = ``\$left``[``\$i``] * ` `                    ``\$right``[``\$i``]; `   `    ``// print the constructed prod array ` `    ``for` `(``\$i` `= 0; ``\$i` `< ``\$n``; ``\$i``++) ` `        ``echo` `\$prod``[``\$i``], ``" "``; `   `    ``return``; ` `} `   `// Driver Code ` `\$arr` `= ``array``(10, 3, 5, 6, 2); ` `\$n` `= ``count``(``\$arr``); ` `echo` `"The product array is : \n"``; ` `productArray(``\$arr``, ``\$n``); `   `// This code has been contributed by anuj_67. ` `?>`

## Javascript

 ``

Output

```The product array is:
180 600 360 300 900 ```

Complexity Analysis:

• Time Complexity: O(n).
The array needs to be traversed three times, so the time complexity is O(n).
• Auxiliary Space: O(n).
Two extra arrays and one array to store the output is needed so the space complexity is O(n)

Note: The above method can be optimized to work in space complexity O(1). Thanks to Dileep for suggesting the below solution.

Efficient Approach: In the previous solution, two extra arrays were created to store the prefix and suffix, in this solution store the prefix and suffix product in the output array (or product array) itself. Thus reducing the space required.

Algorithm:

1. Create an array product and initialize its value to 1 and a variable temp = 1.
2. Traverse the array from start to end.
3. For every index i update product[i] as product[i] = temp and temp = temp * array[i], i.e store the product upto i-1 index from the start of array.
4. initialize temp = 1 and traverse the array from last index to start.
5. For every index i update product[i] as product[i] = product[i] * temp and temp = temp * array[i], i.e multiply with the product upto i+1 index from the end of array.
6. Print the product array.

## C++

 `// C++ implementation of above approach` `#include ` `using` `namespace` `std;`   `/* Function to print product array` `for a given array arr[] of size n */` `void` `productArray(``int` `arr[], ``int` `n)` `{`   `    ``// Base case` `    ``if` `(n == 1) {` `        ``cout << 0;` `        ``return``;` `    ``}`   `    ``int` `i, temp = 1;`   `    ``/* Allocate memory for the product array */` `    ``int``* prod = ``new` `int``[(``sizeof``(``int``) * n)];`   `    ``/* Initialize the product array as 1 */` `    ``memset``(prod, 1, n);`   `    ``/* In this loop, temp variable contains product of` `       ``elements on left side excluding arr[i] */` `    ``for` `(i = 0; i < n; i++) {` `        ``prod[i] = temp;` `        ``temp *= arr[i];` `    ``}`   `    ``/* Initialize temp to 1` `    ``for product on right side */` `    ``temp = 1;`   `    ``/* In this loop, temp variable contains product of` `       ``elements on right side excluding arr[i] */` `    ``for` `(i = n - 1; i >= 0; i--) {` `        ``prod[i] *= temp;` `        ``temp *= arr[i];` `    ``}`   `    ``/* print the constructed prod array */` `    ``for` `(i = 0; i < n; i++)` `        ``cout << prod[i] << ``" "``;`   `    ``return``;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `arr[] = { 10, 3, 5, 6, 2 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``cout << ``"The product array is: \n"``;` `    ``productArray(arr, n);` `}`   `// This code is contributed by rathbhupendra`

## C

 `// C implementation of above approach` `#include ` `#include ` `// Function to print product array for a given array arr[]` `// of size n` `void` `productArray(``int` `arr[], ``int` `n)` `{`   `    ``// Base case` `    ``if` `(n == 1) {` `        ``printf``(``"0"``);` `        ``return``;` `    ``}`   `    ``int` `i, temp = 1;`   `    ``/* Allocate memory for the product array */` `    ``int` `prod[n];`   `    ``/* Initialize the product array as 1 */` `    ``memset``(prod, 1, n);`   `    ``/* In this loop, temp variable contains product of` `       ``elements on left side excluding arr[i] */` `    ``for` `(i = 0; i < n; i++) {` `        ``prod[i] = temp;` `        ``temp *= arr[i];` `    ``}`   `    ``/* Initialize temp to 1` `    ``for product on right side */` `    ``temp = 1;`   `    ``/* In this loop, temp variable contains product of` `       ``elements on right side excluding arr[i] */` `    ``for` `(i = n - 1; i >= 0; i--) {` `        ``prod[i] *= temp;` `        ``temp *= arr[i];` `    ``}`   `    ``/* print the constructed prod array */` `    ``for` `(i = 0; i < n; i++)` `        ``printf``(``"%d "``, prod[i]);`   `    ``return``;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `arr[] = { 10, 3, 5, 6, 2 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``printf``(``"The product array is: \n"``);` `    ``productArray(arr, n);` `}`   `// This code is contributed by Aditya Kumar (adityakumar129)`

## Java

 `class` `ProductArray {` `    ``void` `productArray(``int` `arr[], ``int` `n)` `    ``{`   `        ``// Base case` `        ``if` `(n == ``1``) {` `            ``System.out.print(``"0"``);` `            ``return``;` `        ``}`   `        ``int` `i, temp = ``1``;`   `        ``/* Allocate memory for the product array */` `        ``int` `prod[] = ``new` `int``[n];`   `        ``/* Initialize the product array as 1 */` `        ``for` `(``int` `j = ``0``; j < n; j++)` `            ``prod[j] = ``1``;`   `        ``/* In this loop, temp variable contains product of` `           ``elements on left side excluding arr[i] */` `        ``for` `(i = ``0``; i < n; i++) {` `            ``prod[i] = temp;` `            ``temp *= arr[i];` `        ``}`   `        ``/* Initialize temp to 1 for product on right side */` `        ``temp = ``1``;`   `        ``/* In this loop, temp variable contains product of` `           ``elements on right side excluding arr[i] */` `        ``for` `(i = n - ``1``; i >= ``0``; i--) {` `            ``prod[i] *= temp;` `            ``temp *= arr[i];` `        ``}`   `        ``/* print the constructed prod array */` `        ``for` `(i = ``0``; i < n; i++)` `            ``System.out.print(prod[i] + ``" "``);`   `        ``return``;` `    ``}`   `    ``/* Driver program to test above functions */` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``ProductArray pa = ``new` `ProductArray();` `        ``int` `arr[] = { ``10``, ``3``, ``5``, ``6``, ``2` `};` `        ``int` `n = arr.length;` `        ``System.out.println(``"The product array is : "``);` `        ``pa.productArray(arr, n);` `    ``}` `}`   `// This code has been contributed by Mayank Jaiswal`

## Python3

 `# Python3 program for A Product Array Puzzle` `def` `productArray(arr, n):`   `    ``# Base case` `    ``if` `n ``=``=` `1``:` `        ``print``(``0``)` `        ``return`   `    ``i, temp ``=` `1``, ``1`   `    ``# Allocate memory for the product array` `    ``prod ``=` `[``1` `for` `i ``in` `range``(n)]`   `    ``# Initialize the product array as 1`   `    ``# In this loop, temp variable contains product of` `    ``# elements on left side excluding arr[i]` `    ``for` `i ``in` `range``(n):` `        ``prod[i] ``=` `temp` `        ``temp ``*``=` `arr[i]`   `    ``# Initialize temp to 1 for product on right side` `    ``temp ``=` `1`   `    ``# In this loop, temp variable contains product of` `    ``# elements on right side excluding arr[i]` `    ``for` `i ``in` `range``(n ``-` `1``, ``-``1``, ``-``1``):` `        ``prod[i] ``*``=` `temp` `        ``temp ``*``=` `arr[i]`   `    ``# Print the constructed prod array` `    ``for` `i ``in` `range``(n):` `        ``print``(prod[i], end``=``" "``)`   `    ``return`     `# Driver Code` `arr ``=` `[``10``, ``3``, ``5``, ``6``, ``2``]` `n ``=` `len``(arr)` `print``(``"The product array is: n"``)` `productArray(arr, n)`   `# This code is contributed by mohit kumar`

## C#

 `using` `System;`   `class` `GFG {`   `    ``static` `void` `productArray(``int``[] arr, ``int` `n)` `    ``{`   `        ``// Base case` `        ``if` `(n == 1) {` `            ``Console.Write(0);` `            ``return``;` `        ``}` `        ``int` `i, temp = 1;`   `        ``/* Allocate memory for the product` `        ``array */` `        ``int``[] prod = ``new` `int``[n];`   `        ``/* Initialize the product array as 1 */` `        ``for` `(``int` `j = 0; j < n; j++)` `            ``prod[j] = 1;`   `        ``/* In this loop, temp variable contains` `        ``product of elements on left side` `        ``excluding arr[i] */` `        ``for` `(i = 0; i < n; i++) {` `            ``prod[i] = temp;` `            ``temp *= arr[i];` `        ``}`   `        ``/* Initialize temp to 1 for product on` `        ``right side */` `        ``temp = 1;`   `        ``/* In this loop, temp variable contains` `        ``product of elements on right side` `        ``excluding arr[i] */` `        ``for` `(i = n - 1; i >= 0; i--) {` `            ``prod[i] *= temp;` `            ``temp *= arr[i];` `        ``}`   `        ``/* print the constructed prod array */` `        ``for` `(i = 0; i < n; i++)` `            ``Console.Write(prod[i] + ``" "``);`   `        ``return``;` `    ``}`   `    ``/* Driver program to test above functions */` `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = { 10, 3, 5, 6, 2 };` `        ``int` `n = arr.Length;` `        ``Console.WriteLine(``"The product array is : "``);`   `        ``productArray(arr, n);` `    ``}` `}`   `// This code is contributed by nitin mittal.`

## PHP

 `= 0; ``\$i``--) ` `        ``{` `            ``\$prod``[``\$i``] *= ``\$temp``;` `            ``\$temp` `*= ``\$arr``[``\$i``];` `        ``}`   `        ``/* print the constructed` `           ``prod array */` `        ``for` `(``\$i` `= 0; ``\$i` `< ``\$n``; ``\$i``++)` `            ``echo` `\$prod``[``\$i``], ``" "``;`   `        ``return``;` `    ``}`   `        ``// Driver Code    ` `        ``\$arr` `= ``array``(10, 3, 5, 6, 2);` `        ``\$n` `= ``count``(``\$arr``);` `        ``echo` `"The product array is : \n"``;` `        ``productArray(``\$arr``, ``\$n``);` `    `  `// This code is contributed by anuj_67.` `?>`

## Javascript

 ``

Output

```The product array is:
180 600 360 300 900 ```

Complexity Analysis:

• Time Complexity: O(n).
The original array needs to be traversed only once, so the time complexity is constant.
• Auxiliary Space: O(n).
Even though the extra arrays are removed, the space complexity remains O(n), as the product array is still needed.

A product array puzzle | Set 2 (O(1) Space)
Related Problem:
Construct an Array from XOR of all elements of array except element at same index
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.

My Personal Notes arrow_drop_up
Related Articles