Given an array arr[] consisting of N integers, the task is to construct a Product array of the same size without using division ('/') operator such that each array element becomes equal to the product of all the elements of arr[] except arr[i].
Examples:
Input: arr[] = {10, 3, 5, 6, 2}
Output: 180 600 360 300 900
Explanation:
3 * 5 * 6 * 2 is the product of all array elements except 10 is 180
10 * 5 * 6 * 2 is the product of all array elements except 3 is 600.
10 * 3 * 6 * 2 is the product of all array elements except 5 is 360.
10 * 3 * 5 * 2 is the product of all array elements except 6 is 300.
10 * 3 * 6 * 5 is the product of all array elements except 2 is 9.
Input: arr[] = {1, 2, 1, 3, 4}
Output: 24 12 24 8 6
Approach: The idea is to use log() and exp() functions instead of log10() and pow(). Below are some observations regarding the same:
- Suppose M is the multiplication of all the array elements then the element of output array at ith position will be equal M/arr[i].
- The divisions of two numbers can be performed by using the property of logarithm and exp functions.
- The logarithmic function is not defined for numbers less than zero so to maintain the such cases separately.
Follow the steps below to solve the problem:
- Initialize two variables, say product = 1 and Z = 1, to store the product of array and count of zero elements.
- Traverse the array and multiply the product by arr[i] if arr[i] is not equal to 0. Otherwise, increment count of Z by one.
- Traverse the array arr[] and perform the following:
- If Z is 1 and arr[i] is not zero then update arr[i] as arr[i] = 0 and continue.
- Otherwise, if Z is 1 and arr[i] is 0 then update arr[i] as product and continue.
- Otherwise, if Z is greater than 1 then assign arr[i] as 0 and continue.
- Now find the value of abs(product)/abs(arr[i]) using the formula discussed above and store it in a variable say curr.
- If the value of arr[i] and product is negative or if arr[i] and product is positive then assign arr[i] as curr.
- Otherwise, assign arr[i] as -1*curr.
- After completing the above steps, print the array arr[].
Below is the implementation of the above approach:
Output: 180 600 360 300 900
Time Complexity: O(N)
Auxiliary Space: O(1)
Alternate Approaches: Please refer to the previous posts of this article for alternate approaches: