🎉 One-stop destination for all your technical interview Preparation 🎉
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.
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;
}
};
ans[i-1] and right[i+1]
here right[i+1]=prod
so ans[i] = ans[i - 1] * prod;
ans[0]=prod
itselfclass 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;
}
};
[[C++/Python] 4 Simple Solutions w/ Explanation | Prefix & Suffix product O(1) space approach](https://leetcode.com/problems/product-of-array-except-self/discuss/1597994/C%2B%2B-3-Simple-Solutions-w-Explanation-or-Prefix-and-Suffix-product-O(1)-space-approach) |