238. Product of Array Except Self
Problem Statement
- 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]
.
Approach
- There can be 2 cases
- There are zeroes in the array
- If there is more than 1 zero in the array the entire array product would be 0 (as there would always be one zero to be multiplied even if current element is zero)
- If there is one zero, all the products would be 0 except for the one where the current value is zero
- There are no zeroes in the array
- All products would be non-zero values
- Start by calculating the product of the entire array O(n) skipping the zeroes. then for each entry in the array calculate it's product value O(n)
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
long long product = 1;
vector<int> result;
int countZeroes = 0;
for(auto a : nums)
if(a != 0)
product *= a;
else
countZeroes++;
if(countZeroes > 1){
vector<int> result(nums.size(), 0);
return result;
}
for(auto a : nums){
if(a != 0){
if(countZeroes)
result.push_back(0);
else
result.push_back(product/a);
}else{
result.push_back(product);
}
}
return result;
}
};