Simple two pass O(n) time O(1) space solution in C++


  • 2
    A
      vector<int> productExceptSelf(vector<int>& nums) {
            int n=nums.size();
            vector<int> ans;
            ans.push_back(1);
            if(n<=1)
            return nums;
            
            for(int i=1;i<n;i++)
            {
               ans.push_back(ans[i-1]*nums[i-1]); 
            }
            
            for(int i=n-2;i>=0;i--)
            {
                nums[i]=nums[i]*nums[i+1];
                ans[i]=ans[i]*nums[i+1];
            }
            
            return ans;
            
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.