Product of Array Except Self

Product of Array Except Self

Product of Array Except Self

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

Hint:

Code:

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

        int n = nums.size();
        vector<int> ans(n,1);

        int left = nums[0];
        int right = nums[n-1];

        for(int i=n-2;i>=0;i--){
            ans[i] = ans[i]*right;
            right = right*nums[i];
        }

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

        return ans;
    }
};