Problem Statement

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Example 1:

Input: nums = [1,2,3,4]
Output: [24,12,8,6]

Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Constraints:

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

Problem Link

https://leetcode.com/problems/product-of-array-except-self/description/

Code

Using O(n) time and space complexity

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {

        int n = nums.size();

        vector<int> preProd(n,1), postProd(n,1);
        preProd[0] = nums[0];
        postProd[n-1] = nums[n-1];

        for(int i=1;i<n;i++) {
            preProd[i] = preProd[i-1] * nums[i];
        }

        for(int i=n-2;i>=0;i--) {
            postProd[i] = postProd[i+1] * nums[i];
        }

        vector<int> res(n,1);

        for(int i=0;i<n;i++) {
            int a = 1, b = 1;
            if(i-1>=0) {
                a = preProd[i-1];
            }

            if(i+1<n) {
                b = postProd[i+1];
            }
            res[i] = a*b;
        }

       return res;

        
        
    }
};

Using O(n) time and O(1) space complexity

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size();
        vector<int> prod(n);
        int cur = 1;

        for(int i = 0; i < n; i++){
            prod[i] = cur;
            cur *= nums[i];
        }

        cur = 1;
        for(int i = n - 1; i >= 0; i--){
            prod[i] *= cur;
            cur *= nums[i];
        }

        return prod;
    }
};