classSolution{public:vector<int>productExceptSelf(vector<int>&nums){intn=nums.size();vector<int>answer(n);// This will store our, products of each `i` except the element at `i`// We will pick each number from left -> rightfor(inti=0;i<n;i++){// for each `i` to calculate new productintproduct=1;// This will go from start to end againfor(intj=0;j<n;j++){// if `i` and `j` index are not same// We can calculate the product of other elementsif(i!=j){product*=nums[j];}}// put the `product` in the `answer` arrayanswer[i]=product;}returnanswer;// Done!}};
classSolution{public:vector<int>productExceptSelf(vector<int>&nums){intn=nums.size();intzeroCount=0;// It will count how many zeros are there in arrayintproductWithoutZero=1;// It will store, product of all elements except zero(s)// Pass 1:// Count the zeros// Calculate the non-zero elements productfor(intnum:nums){// if `num` is zeroif(num==0){zeroCount++;// Increment the count of `zeroCount`}else{productWithoutZero*=num;// Multiply it with with non-zero elements}}// Create a result array to store the answersvector<int>result(n);// Pass 2:for(inti=0;i<n;i++){// If this current element is not zeroif(nums[i]!=0){// Check, is there any zero present somewhere?if(zeroCount>0){result[i]=0;// result will be directly zero, cause anything multiply by zero is zero}else{result[i]=productWithoutZero/nums[i];// Cancle out the `nums[i]` from `productWithoutZero`}}else{// If this current element is zero// Check, is there also another zero present somewhere?if(zeroCount>1){result[i]=0;// result will be directly zero}else{result[i]=productWithoutZero;// product of all other elements}}}returnresult;// Done}};
classSolution{public:vector<int>productExceptSelf(vector<int>&nums){intn=nums.size();vector<int>answer(n);// This will store answersanswer[0]=1;// because the first element do not have anyone before it// Pass 1: Left products// We will calculate the prefix product at each `i`for(inti=1;i<n;i++){answer[i]=answer[i-1]*nums[i-1];}// Pass 2: Right products & Final answerintrightProduct=1;// because the last element do not have anyone after it// We will calculate the suffix product at each `i`for(inti=n-1;i>=0;i--){answer[i]=answer[i]*rightProduct;// Multiply `rightProduct` with stored `answer[i]`// Update the `rightProduct` for next itrationrightProduct=rightProduct*nums[i];}returnanswer;// Done}};
Warning
LINK
You are about to visit a link which has been flagged with the above content warnings. Do you wish to continue?