A Product Array Puzzle | Javascript program for the above approach ; Product of all elements ; Counting number of elements which have value 0 ; Creating a new array of size n ; If number of elements in array with value 0 is more than 1 than each value in new array will be equal to 0 ; If no element having value 0 than we will insert product / a [ i ] in new array ; If 1 element of array having value 0 than all the elements except that index value , will be equal to 0 ; If ( flag == 1 && a [ i ] == 0 ) ; Driver code
function productExceptSelf ( a , n ) { let prod = 1 ; let flag = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) flag ++ ; else prod *= a [ i ] ; } let arr = Array ( n ) . fill ( 0 ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( flag > 1 ) { arr [ i ] = 0 ; } else if ( flag == 0 ) arr [ i ] = ( prod / a [ i ] ) ; else if ( flag == 1 && a [ i ] != 0 ) { arr [ i ] = 0 ; } else arr [ i ] = prod ; } return arr ; } let n = 5 ; let array = [ 10 , 3 , 5 , 6 , 2 ] ; let ans = Array ( n ) . fill ( 0 ) ; ans = productExceptSelf ( array , n ) ; for ( let i = 0 ; i < n ; i ++ ) { document . write ( ans [ i ] + " " ) ; }