VOOZH about

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

⇱ Product of Array Except Self - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Product of Array Except Self

Last Updated : 27 Jan, 2026

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

Example:

Input: arr[] = [10, 3, 5, 6, 2]
Output: [180, 600, 360, 300, 900]
Explanation:
For i=0, res[i] = 3 * 5 * 6 * 2 is 180.
For i = 1, res[i] = 10 * 5 * 6 * 2 is 600.
For i = 2, res[i] = 10 * 3 * 6 * 2 is 360.
For i = 3, res[i] = 10 * 3 * 5 * 2 is 300.
For i = 4, res[i] = 10 * 3 * 5 * 6 is 900.

Input: arr[] = [12, 0]
Output: [0, 12]
Explanation:
For i = 0, res[i] = 0.
For i = 1, res[i] = 12.

[Naive Approach] Using Nested Loops - O(n^2) Time and O(n) Space

The idea is to compute the product of all elements except the current one by fixing the index and multiplying all other elements in the array. Doing this for every position generates the required result array.


Output
180 600 360 300 900 

[Better approach] Using Prefix and Suffix Array - O(n) Time and O(n) Space

The idea is to precompute the prefix and suffix products and store them in two arrays. Now we can find the product of array except i-th element, by using these precomputed arrays in constant time.
product of array except i-th element = prefProduct[i] * suffProduct[i]

prefProduct[i] stores product of all elements before i-th index in the array.
suffProduct[i] stores product of all elements after i-th index in the array.


Output
180 600 360 300 900 

[Efficient Approach] Using Product Array - O(n) Time and O(1) Space

The idea is to handle two special cases of the input array: when it contains zero(s) and when it doesn't. If the array has no zeros, product of array at any index (excluding itself) can be calculated by dividing the total product of all elements by the current element.

  • However, division by zero is undefined, so if there are zeros in the array, the logic changes.
  • If there is exactly one zero, the product for that index will be the product of all other non-zero elements, while the elements in rest of the indices will be zero.
  • If there are more than one zero, the product for all indices will be zero, since multiplying by zero results in zero.

Output
180 600 360 300 900 

Other Mathematical Approaches: Please refer A product array puzzle for more approaches that use log and pow to compute the required result without division operator.

Related Problem: 

Comment