A Product Array Puzzle | Set 3 | Java program to implement 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
import java . util . * ; class GFG { static void productExceptSelf ( int arr [ ] , int N ) { int product = 1 ; int z = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != 0 ) product *= arr [ i ] ; if ( arr [ i ] == 0 ) z += 1 ; } int a = Math . abs ( product ) ; for ( int 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 ; } int b = Math . abs ( arr [ i ] ) ; int curr = ( int ) 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 ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String args [ ] ) { int arr [ ] = { 10 , 3 , 5 , 6 , 2 } ; int N = arr . length ; productExceptSelf ( arr , N ) ; } }