![]() |
VOOZH | about |
Given an array arr[] of size n, 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].
Note: Solve it without division operator and in O(n).
Examples:
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.
Refer to Product of Array Except Self | Set 1 for other approaches.
The idea is to use log operator to find the product of all elements of the array except at a particular index.
How to use log operator for multiplication?
x = a * b * c * d
log(x) = log(a * b * c * d)
log(x) = log(a) + log(b) + log(c) + log(d)
x = antilog(log(a) + log(b) + log(c) + log(d))
Step by step approach:
How are negative numbers handled?
Log value of negative numbers is not defined. So we have to handle them separately.
To handle negative numbers, we take the log of the absolute value of each element and separately track the sign of the overall product. While computing the final result for each index, we adjust the sign based on whether the excluded element was negative, ensuring the correct sign is applied without affecting the logarithmic calculation.
180 600 360 300 900
The idea is to traverse the array and find the product of all the elements in the array. Then traverse the array again and find the product of all the elements except that number by using the formula (product * pow(a[i], -1)).
Step by step approach:
180 600 360 300 900