O(n) time and O(1) space simple count number of zeroes solution


  • 0
    P

    '''

        vector<int> productExceptSelf(vector<int>& nums) 
        {
            int n = nums.size();
            vector<int> q(n);
            if(!n)
                return q;
            int idx = -1;
            long prod = 1;
    
            for(int i=0; i<n; i++)
                /*store index of first zero*/
                if(idx==-1 && !nums[i])
                    idx = i;
                else
                    prod*=nums[i];
        
            for(int i=0; i<n; i++)
                /*if zero present, all other indices result in zero*/
                if(idx!=-1 && i!=idx)
                    q[i] = 0;
                else if(nums[i])
                    q[i] = prod / nums[i];
                /*value at zero's index will be remaining prod*/
                else
                    q[i] = prod;
        
            return q;
        }
    

    '''


Log in to reply
 

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