![]() |
VOOZH | about |
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.
Table of Content
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.
180 600 360 300 900
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.
180 600 360 300 900
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.
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: