238. Product of Array Except Self
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Arrays & Hashing
- Time
- O(N)
- Space
- O(1)
A standard reference solution for this problem is coming soon.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
// use two vectors to store the prefix prod and suffix prod
// specifically, prefix[i]=nums[0]*nums[1]*...*nums[i-1]
// right[i]=nums[i+1]*nums[i+2]*...*nums[n-1]
// to acheive the O(1) space, we must utilize the output array
// for example, nums = [1,2,3,4]
// init: ans = [1, 1, 1, 1]
// calc the prefix prod: ans = [1, 1, 2, 6]
// calc the suffix prod: use extra var "suffix"
// from the back, ans[n-1] is unchanged, suffix=nums[n-1]
// ans[n-2]*=suffix, suffix*=nums[n-2]
// keep the loop until hit the beginning
int n=nums.size();
vector<int> ans(n, 1);
for(int i=1; i<n; ++i){
ans[i]=ans[i-1]*nums[i-1];
}
int suffix=nums[n-1];
for(int j=n-2; j>=0; --j){
ans[j]*=suffix;
suffix*=nums[j];
}
return ans;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) Time O(N) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.