Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

238. Product of Array Except Self 🌟🌟

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.

Intuitive Solution

Using Extra space

Code

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums)
    {
        int n = nums.size();
        vector<int> left(n), right(n);
        vector<int> ans(n);
        int prod = 1;
        for (int i = 0; i < n; i++) {
            prod *= nums[i];
            left[i] = prod;
        }
        prod = 1;
        for (int i = n - 1; i >= 0; i--) {
            prod *= nums[i];
            right[i] = prod;
        }

        ans[0] = right[1], ans[n - 1] = left[n - 2];
        for (int i = 1; i < n - 1; i++) {
            ans[i] = left[i - 1] * right[i + 1];
        }
        return ans;
    }
};

Space optimization

Code

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

        int prod = 1;
        for (int i = 0; i < n; ++i) {
            prod *= nums[i];
            ans.push_back(prod);
        }

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

Read