Advertisement
imashutosh51

Product of Array Except self

Oct 16th, 2022 (edited)
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> productExceptSelf(vector<int>& input) {
  4.         int n=input.size();
  5.         vector <int> ans(n,1);
  6.         int temp=1;
  7.         for(int i=0;i<n;i++){
  8.             ans[i]=temp;
  9.             temp*=input[i];
  10.         }
  11.         for(auto itr:ans) cout<<itr<<" ";
  12.         cout<<endl;
  13.        
  14.         temp=1;
  15.         for(int i=n-1;i>=0;i--){
  16.             ans[i]*=temp;
  17.             temp*=input[i];
  18.         }
  19.         return ans;
  20.     }
  21. };
  22.  
  23. #Python
  24. class Solution:
  25.     def productExceptSelf(self, nums: List[int]) -> List[int]:
  26.         zero=0
  27.         mul=1
  28.         for i in nums:
  29.             if i==0:
  30.                 zero+=1
  31.             else:
  32.                 mul=mul*i
  33.         if zero==0:
  34.             return [mul//i for i in nums]
  35.         if zero==1:
  36.             return [0 if i!=0 else mul for i in nums]
  37.         else:
  38.             return [0 for i in nums] #We can avoid using range(len(nums)) also
  39.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement