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

Last Updated : 24 Apr, 2025

Given an array arr[] of size n, construct a product array res[] (of the same size) such that res[i] is equal to the product of all the elements of arr[] except arr[i]. 

Note: Solve it without division operator and in O(n).

Examples: 

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

  • For i=0, res[i] = 3 * 5 * 6 * 2 is 180.
  • For i = 1, res[i] = 10 * 5 * 6 * 2 is 600.
  • For i = 2, res[i] = 10 * 3 * 6 * 2 is 360.
  • For i = 3, res[i] = 10 * 3 * 5 * 2 is 300.
  • For i = 4, res[i] = 10 * 3 * 5 * 6 is 900.

Input: arr[] = [12, 0]
Output: [0, 12]
Explanation:

  • For i = 0, res[i] = 0.
  • For i = 1, res[i] = 12.
Try It Yourself
redirect icon

Refer to Product of Array Except Self | Set 1 for other approaches.

[Expected Approach - 1] Using Log Operator - O(n) time and O(1) space

The idea is to use log operator to find the product of all elements of the array except at a particular index.

How to use log operator for multiplication?

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))

Step by step approach:

  1. Traverse the array and find the sum of log of all the elements,   
    • log(a[0]) + log(a[1]) + .. + log(a[n-1])
  2. Then again traverse through the array and find the product using this formula.  
    • antilog((log(a[0]) + log(a[1]) + .. + log(a[n-1])) - log(a[i]))
  3. This equals to product of all the elements except a[i], i.e., antilog(sum- log(a[i])). 

How are negative numbers handled?

Log value of negative numbers is not defined. So we have to handle them separately.

To handle negative numbers, we take the log of the absolute value of each element and separately track the sign of the overall product. While computing the final result for each index, we adjust the sign based on whether the excluded element was negative, ensuring the correct sign is applied without affecting the logarithmic calculation.

C++
// C++ program for product array puzzle using logarithms
// with O(n) time and O(1) space.
#include <bits/stdc++.h>
using namespace std;

vector<int> productExceptSelf(vector<int>& arr) {
    int n = arr.size();
    vector<int> ans(n);

    // Handle zeros
    int zeroCnt = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] == 0) zeroCnt++;
    }

    if (zeroCnt > 1) {
        fill(ans.begin(), ans.end(), 0);
        return ans;
    }

    if (zeroCnt == 1) {
        int prod = 1, zeroIndex = -1;
        for (int i = 0; i < n; i++) {
            if (arr[i] != 0) prod *= arr[i];
            else zeroIndex = i;
        }
        ans[zeroIndex] = prod;
        return ans;
    }

    // No zero case, handle sign and logs
    double sumLog = 0.0;
    int signProduct = 1;
    for (int i = 0; i < n; i++) {
        sumLog += log10(abs(arr[i]));
        if (arr[i] < 0) signProduct *= -1;
    }

    for (int i = 0; i < n; i++) {
        double logVal = sumLog - log10(abs(arr[i]));
        int sign = (arr[i] < 0) ? -signProduct : signProduct;
        double res = pow(10.0, logVal);
        ans[i] = (int)(sign * (res + 0.5)); 
    }

    return ans;
}

int main() {
    vector<int> arr = { 10, 3, 5, 6, 2 };
    vector<int> ans = productExceptSelf(arr);
    for (int x : ans) {
        cout << x << " ";
    }
    return 0;
}
Java
// Java program for product array puzzle using logarithms
// with O(n) time and O(1) space.
import java.util.*;

class GfG {

    static int[] productExceptSelf(int[] arr) {
        int n = arr.length;
        int[] ans = new int[n];

        // Handle zeros
        int zeroCnt = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] == 0) zeroCnt++;
        }

        if (zeroCnt > 1) {
            Arrays.fill(ans, 0);
            return ans;
        }

        if (zeroCnt == 1) {
            int prod = 1, zeroIndex = -1;
            for (int i = 0; i < n; i++) {
                if (arr[i] != 0) prod *= arr[i];
                else zeroIndex = i;
            }
            ans[zeroIndex] = prod;
            return ans;
        }

        // No zero case, handle sign and logs
        double sumLog = 0.0;
        int signProduct = 1;
        for (int i = 0; i < n; i++) {
            sumLog += Math.log10(Math.abs(arr[i]));
            if (arr[i] < 0) signProduct *= -1;
        }

        for (int i = 0; i < n; i++) {
            double logVal = sumLog - Math.log10(Math.abs(arr[i]));
            int sign = (arr[i] < 0) ? -signProduct : signProduct;
            double res = Math.pow(10.0, logVal);
            ans[i] = (int)(sign * (res + 0.5));
        }

        return ans;
    }

    public static void main(String[] args) {
        int[] arr = { 10, 3, 5, 6, 2 };
        int[] ans = productExceptSelf(arr);
        for (int x : ans) {
            System.out.print(x + " ");
        }
    }
}
Python
# Python program for product array puzzle using logarithms
# with O(n) time and O(1) space.
import math

def productExceptSelf(arr):
    n = len(arr)
    ans = [0] * n

    # Handle zeros
    zeroCnt = 0
    for i in range(n):
        if arr[i] == 0:
            zeroCnt += 1

    if zeroCnt > 1:
        return ans

    if zeroCnt == 1:
        prod = 1
        zeroIndex = -1
        for i in range(n):
            if arr[i] != 0:
                prod *= arr[i]
            else:
                zeroIndex = i
        ans[zeroIndex] = prod
        return ans

    # No zero case, handle sign and logs
    sumLog = 0.0
    signProduct = 1
    for i in range(n):
        sumLog += math.log10(abs(arr[i]))
        if arr[i] < 0:
            signProduct *= -1

    for i in range(n):
        logVal = sumLog - math.log10(abs(arr[i]))
        sign = -signProduct if arr[i] < 0 else signProduct
        res = pow(10.0, logVal)
        ans[i] = int(sign * (res + 0.5))

    return ans

if __name__ == "__main__":
    arr = [10, 3, 5, 6, 2]
    ans = productExceptSelf(arr)
    for x in ans:
        print(x, end=' ')
C#
// C# program for product array puzzle using logarithms
// with O(n) time and O(1) space.
using System;

class GfG {

    static int[] productExceptSelf(int[] arr) {
        int n = arr.Length;
        int[] ans = new int[n];

        // Handle zeros
        int zeroCnt = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] == 0) zeroCnt++;
        }

        if (zeroCnt > 1) {
            Array.Fill(ans, 0);
            return ans;
        }

        if (zeroCnt == 1) {
            int prod = 1, zeroIndex = -1;
            for (int i = 0; i < n; i++) {
                if (arr[i] != 0) prod *= arr[i];
                else zeroIndex = i;
            }
            ans[zeroIndex] = prod;
            return ans;
        }

        // No zero case, handle sign and logs
        double sumLog = 0.0;
        int signProduct = 1;
        for (int i = 0; i < n; i++) {
            sumLog += Math.Log10(Math.Abs(arr[i]));
            if (arr[i] < 0) signProduct *= -1;
        }

        for (int i = 0; i < n; i++) {
            double logVal = sumLog - Math.Log10(Math.Abs(arr[i]));
            int sign = (arr[i] < 0) ? -signProduct : signProduct;
            double res = Math.Pow(10.0, logVal);
            ans[i] = (int)(sign * (res + 0.5));
        }

        return ans;
    }

    static void Main(string[] args) {
        int[] arr = { 10, 3, 5, 6, 2 };
        int[] ans = productExceptSelf(arr);
        foreach (int x in ans) {
            Console.Write(x + " ");
        }
    }
}
JavaScript
// JavaScript program for product array puzzle using logarithms
// with O(n) time and O(1) space.

function productExceptSelf(arr) {
    const n = arr.length;
    const ans = new Array(n);

    // Handle zeros
    let zeroCnt = 0;
    for (let i = 0; i < n; i++) {
        if (arr[i] === 0) zeroCnt++;
    }

    if (zeroCnt > 1) {
        return ans.fill(0);
    }

    if (zeroCnt === 1) {
        let prod = 1, zeroIndex = -1;
        for (let i = 0; i < n; i++) {
            if (arr[i] !== 0) prod *= arr[i];
            else zeroIndex = i;
        }
        ans.fill(0);
        ans[zeroIndex] = prod;
        return ans;
    }

    // No zero case, handle sign and logs
    let sumLog = 0.0;
    let signProduct = 1;
    for (let i = 0; i < n; i++) {
        sumLog += Math.log10(Math.abs(arr[i]));
        if (arr[i] < 0) signProduct *= -1;
    }

    for (let i = 0; i < n; i++) {
        let logVal = sumLog - Math.log10(Math.abs(arr[i]));
        let sign = (arr[i] < 0) ? -signProduct : signProduct;
        let res = Math.pow(10.0, logVal);
        ans[i] = Math.round(sign * res);
    }

    return ans;
}

const arr = [10, 3, 5, 6, 2];
const ans = productExceptSelf(arr);
console.log(ans.join(' '));

Output
180 600 360 300 900 

[Expected Approach - 2] Using Power Function - O(n) time and O(1) space

The idea is to traverse the array and find the product of all the elements in the array. Then traverse the array again and find the product of all the elements except that number by using the formula (product * pow(a[i], -1)).

Step by step approach:

  1. Store the product of all values of array in a variable. Also find the number of zeros in the array.
  2. If the number of zeros is greater than 1, then return an array of zeros. If number of zeros is 1, then the index at which zero is present will have the value of the product of all values.
  3. If the number of zeros is 0, then for each value in the array, the product will be equal to (total product) * (power(arr[i], -1)).
C++
// C++ program for product array puzzle
// with O(n) time and O(1) space.
#include <bits/stdc++.h>
using namespace std;

vector<int> productExceptSelf(vector<int>& arr) {
    int n = arr.size();

    // Initialize a variable to store the
    // total product of the array elements
    int prod = 1;
    
    // Variable to count number of zeros
    int zeroCnt = 0, zeroIndex = -1;
    for (int i = 0; i < n; i++) {
        if (arr[i] != 0) {
            prod *= arr[i];
        }
        else {
            zeroCnt++;
            zeroIndex = i;
        }
    }
    
    vector<int> ans(n, 0);
    
    if (zeroCnt == 0) {
        
        // we know x/y mathematically is same
        // as x*(y to power -1)
        for (int i = 0; i < n; i++) {
            ans[i] = (int)(prod * pow(arr[i], -1));
        }
    }
    else if (zeroCnt == 1) {
        
        // All values except 0 will be 0.
        ans[zeroIndex] = prod;
    }
    
    return ans;
}

int main() {
    int n = 5;
    vector<int> arr = { 10, 3, 5, 6, 2 };
    vector<int> ans = productExceptSelf(arr);
    for (int i=0; i<n; i++) {
        cout << ans[i] << " ";
    }
    return 0;
}
Java
// Java program for product array puzzle
// with O(n) time and O(1) space.

import java.util.*;

class GfG {

    // Function to return the product array
    static int[] productExceptSelf(int[] arr) {
        int n = arr.length;

        // Initialize a variable to store the
        // total product of the array elements
        int prod = 1;

        // Variable to count number of zeros
        int zeroCnt = 0, zeroIndex = -1;
        for (int i = 0; i < n; i++) {
            if (arr[i] != 0) {
                prod *= arr[i];
            } else {
                zeroCnt++;
                zeroIndex = i;
            }
        }

        int[] ans = new int[n];
        Arrays.fill(ans, 0);

        if (zeroCnt == 0) {

            // we know x/y mathematically is same
            // as x*(y to power -1)
            for (int i = 0; i < n; i++) {
                ans[i] = (int)(prod * Math.pow(arr[i], -1));
            }
        } else if (zeroCnt == 1) {

            // All values except 0 will be 0.
            ans[zeroIndex] = prod;
        }

        return ans;
    }

    public static void main(String[] args) {
        int n = 5;
        int[] arr = {10, 3, 5, 6, 2};
        int[] ans = productExceptSelf(arr);
        for (int i = 0; i < n; i++) {
            System.out.print(ans[i] + " ");
        }
    }
}
Python
# Python program for product array puzzle
# with O(n) time and O(1) space.

def productExceptSelf(arr):
    n = len(arr)

    # Initialize a variable to store the
    # total product of the array elements
    prod = 1

    # Variable to count number of zeros
    zeroCnt = 0
    zeroIndex = -1
    for i in range(n):
        if arr[i] != 0:
            prod *= arr[i]
        else:
            zeroCnt += 1
            zeroIndex = i

    ans = [0] * n

    if zeroCnt == 0:

        # we know x/y mathematically is same
        # as x*(y to power -1)
        for i in range(n):
            ans[i] = int(prod * pow(arr[i], -1))

    elif zeroCnt == 1:

        # All values except 0 will be 0.
        ans[zeroIndex] = prod

    return ans

if __name__ == "__main__":
    n = 5
    arr = [10, 3, 5, 6, 2]
    ans = productExceptSelf(arr)
    for i in range(n):
        print(ans[i], end=" ")
C#
// C# program for product array puzzle
// with O(n) time and O(1) space.

using System;

class GfG {

    // Function to return the product array
    static int[] productExceptSelf(int[] arr) {
        int n = arr.Length;

        // Initialize a variable to store the
        // total product of the array elements
        int prod = 1;

        // Variable to count number of zeros
        int zeroCnt = 0, zeroIndex = -1;
        for (int i = 0; i < n; i++) {
            if (arr[i] != 0) {
                prod *= arr[i];
            } else {
                zeroCnt++;
                zeroIndex = i;
            }
        }

        int[] ans = new int[n];
        for (int i = 0; i < n; i++) {
            ans[i] = 0;
        }

        if (zeroCnt == 0) {

            // we know x/y mathematically is same
            // as x*(y to power -1)
            for (int i = 0; i < n; i++) {
                ans[i] = (int)(prod * Math.Pow(arr[i], -1));
            }

        } else if (zeroCnt == 1) {

            // All values except 0 will be 0.
            ans[zeroIndex] = prod;
        }

        return ans;
    }

    static void Main(string[] args) {
        int n = 5;
        int[] arr = {10, 3, 5, 6, 2};
        int[] ans = productExceptSelf(arr);
        for (int i = 0; i < n; i++) {
            Console.Write(ans[i] + " ");
        }
    }
}
JavaScript
// JavaScript program for product array puzzle
// with O(n) time and O(1) space.

function productExceptSelf(arr) {
    let n = arr.length;

    // Initialize a variable to store the
    // total product of the array elements
    let prod = 1;

    // Variable to count number of zeros
    let zeroCnt = 0, zeroIndex = -1;
    for (let i = 0; i < n; i++) {
        if (arr[i] !== 0) {
            prod *= arr[i];
        } else {
            zeroCnt++;
            zeroIndex = i;
        }
    }

    let ans = new Array(n).fill(0);

    if (zeroCnt === 0) {

        // we know x/y mathematically is same
        // as x*(y to power -1)
        for (let i = 0; i < n; i++) {
            ans[i] = Math.floor(prod * Math.pow(arr[i], -1));
        }

    } else if (zeroCnt === 1) {

        // All values except 0 will be 0.
        ans[zeroIndex] = prod;
    }

    return ans;
}

let n = 5;
let arr = [10, 3, 5, 6, 2];
let ans = productExceptSelf(arr);
for (let i = 0; i < n; i++) {
    console.log(ans[i]);
}

Output
180 600 360 300 900 
Comment