text: A Product Array Puzzle | Set 3 | 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: function productExceptSelf ( arr , N ) { let product = 1 ; let z = 0 ; for ( let i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != 0 ) product *= arr [ i ] ; if ( arr [ i ] == 0 ) z += 1 ; } let a = Math . abs ( product ) ; for ( let i = 0 ; i < N ; i ++ ) { if ( z == 1 ) { if ( arr [ i ] != 0 ) arr [ i ] = 0 ; else arr [ i ] = product ; continue ; } else if ( z > 1 ) { arr [ i ] = 0 ; continue ; } let b = Math . abs ( arr [ i ] ) ; let curr = Math . round ( Math . exp ( Math . log ( a ) - Math . 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 ( let i = 0 ; i < N ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } let arr = [ 10 , 3 , 5 , 6 , 2 ] ; let N = arr . length ; productExceptSelf ( arr , N ) ;