A product array puzzle | Set 2 (O(1) Space)

Given an array arr[] of n integers, construct a Product Array prod[] (of same size) such that prod[i] is equal to the product of all the elements of arr[] except arr[i]. Solve it without division operator and in O(n).

Example:

Input : arr[] = {10, 3, 5, 6, 2}
Output : prod[] = {180, 600, 360, 300, 900}



We have already discussed O(n) approach in A product array puzzle | set 1. The previous approach uses extra O(n) space for constructing product array.

In this post, a better approach has been discussed which uses log property to find the product of all elements of array except at particular index. This approach uses no extra space.

Use property of log to multiply large numbers
x = a * b * c * d
log(x) = log(a * b * c * d)
log(x) = log(a) + log(b) + log(c) + log(d)
x = antilog(log(a) + log(b) + log(c) + log(d))

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for product array puzzle
// with O(n) time and O(1) space.
#include <bits/stdc++.h>
using namespace std;
  
// epsilon value to maintain precision
#define EPS 1e-9
  
void productPuzzle(int a[], int n)
{
    // to hold sum of all values
    long double sum = 0; 
    for (int i = 0; i < n; i++)
        sum += (long double)log10(a[i]);
  
    // output product for each index
    // antilog to find original product value
    for (int i = 0; i < n; i++)
        cout << (int)(EPS + pow((long double)10.00, 
                         sum - log10(a[i]))) << " "
}
  
// Driver code
int main()
{
    int a[] = { 10, 3, 5, 6, 2 };
    int n = sizeof(a)/sizeof(a[0]);
    cout << "The product array is: \n";
    productPuzzle(a, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for product array puzzle
// with O(n) time and O(1) space.
public class Array_puzzle_2 {
  
    // epsilon value to maintain precision
    static final double EPS = 1e-9;
  
    static void productPuzzle(int a[], int n)
    {
        // to hold sum of all values
        double sum = 0
        for (int i = 0; i < n; i++)
            sum += Math.log10(a[i]);
  
        // output product for each index
        // anti log to find original product value
        for (int i = 0; i < n; i++)
            System.out.print((int)(EPS + Math.pow(10.00,
                          sum - Math.log10(a[i]))) + " "); 
    }
  
    // Driver code
    public static void main(String args[])
    {
        int a[] = { 10, 3, 5, 6, 2 };
        int n = a.length;
        System.out.println( "The product array is: ");
        productPuzzle(a, n);
    }
}
// This code is contributed by Sumit Ghosh

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program for product array puzzle
# with O(n) time and O(1) space.
  
import math
  
# epsilon value to maintain precision
EPS = 1e-9
  
def productPuzzle(a, n):
     
    # to hold sum of all values
    sum = 0
    for i in range(n):
        sum += math.log10(a[i])
      
    # output product for each index
    # antilog to find original product value
    for i in range(n):
        print int((EPS + pow(10.00, sum - math.log10(a[i])))),
      
    return
   
# Driver code
a = [10, 3, 5, 6, 2 ]
n = len(a)
print "The product array is: "
productPuzzle(a, n)
  
# This code is contributed by Sachin Bisht

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for product 
// array puzzle with O(n)
// time and O(1) space.
using System;
class GFG
{
  
    // epsilon value to
    // maintain precision
    static double EPS = 1e-9;
  
    static void productPuzzle(int[] a,
                              int n)
    {
        // to hold sum of all values
        double sum = 0; 
        for (int i = 0; i < n; i++)
            sum += Math.Log10(a[i]);
  
        // output product for each 
        // index anti log to find
        // original product value
        for (int i = 0; i < n; i++)
            Console.Write((int)(EPS + Math.Pow(10.00,
                           sum - Math.Log10(a[i]))) + " "); 
    }  
  
    // Driver code
    public static void Main()
    {
        int []a = {10, 3, 5, 6, 2};
        int n = a.Length;
        Console.WriteLine("The product array is: ");
        productPuzzle(a, n);
    }
}
  
// This code is contributed by mits

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program for product array puzzle
// with O(n) time and O(1) space.
  
// epsilon value to maintain precision
$EPS=1e-9;
  
function productPuzzle($a, $n)
{
    global $EPS;
    // to hold sum of all values
    $sum = 0; 
    for ($i = 0; $i < $n; $i++)
        $sum += (double)log10($a[$i]);
  
    // output product for each index
    // antilog to find original product value
    for ($i = 0; $i < $n; $i++)
        echo (int)($EPS + pow((double)10.00, $sum - log10($a[$i])))." "
}
  
// Driver code
  
    $a = array(10, 3, 5, 6, 2 );
    $n = count($a);
    echo "The product array is: \n";
    productPuzzle($a, $n);
  
// This code is contributed by mits
?>

chevron_right



Output:

The product array is: 
180 600 360 300 900 


Time complexity :
O(n)
Space complexity: O(1)

This article is contributed by Abhishek Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : Mithun Kumar