text: A Product Array Puzzle | Set 3 | C ++ program for the above approach ; Function to form product array with O ( n ) time and O ( 1 ) space ; Stores the product of array ; Stores the count of zeros ; Traverse the array ; If arr [ i ] is not zero ; If arr [ i ] is zero then increment count of z by 1 ; Stores the absolute value of the product ; If Z is equal to 1 ; If arr [ i ] is not zero ; Else ; If count of 0 s at least 2 ; Assign arr [ i ] = 0 ; Store absolute value of arr [ i ] ; Find the value of a / b ; If arr [ i ] and product both are less than zero ; If arr [ i ] and product both are greater than zero ; Else ; Traverse the array arr [ ] ; Driver Code ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void productExceptSelf ( int arr [ ] , int N ) { int product = 1 ; int z = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] ) product *= arr [ i ] ; z += ( arr [ i ] == 0 ) ; } int a = abs ( product ) , b ; for ( int i = 0 ; i < N ; i ++ ) { if ( z == 1 ) { if ( arr [ i ] ) arr [ i ] = 0 ; else arr [ i ] = product ; continue ; } else if ( z > 1 ) { arr [ i ] = 0 ; continue ; } int b = abs ( arr [ i ] ) ; int curr = round ( exp ( log ( a ) - log ( b ) ) ) ; if ( arr [ i ] < 0 && product < 0 ) arr [ i ] = curr ; else if ( arr [ i ] > 0 && product > 0 ) arr [ i ] = curr ; else arr [ i ] = -1 * curr ; } for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 10 , 3 , 5 , 6 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; productExceptSelf ( arr , N ) ; return 0 ; }