Leetcode 238 Solution

This article provides solution to leetcode question 238 (product-of-array-except-self)

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

Solution

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> a(nums.size());
        vector<int> b(nums.size());
        vector<int> c(nums.size());

        int curr = 1;
        for (int i = 0; i < nums.size(); i++)
        {
            curr *= nums[i];
            a[i] = curr;
        }

        curr = 1;
        for (int i = nums.size() - 1; i >= 0; i--)
        {
            curr *= nums[i];
            b[i] = curr;
        }

        for (int i = 0; i < nums.size(); i++)
        {
            if (i == 0)
                c[i] = b[i + 1];
            else if (i == nums.size() - 1)
                c[i] = a[i - 1];
            else
                c[i] = b[i + 1] * a[i - 1];

        }

        return c;
    }
};