Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)


class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
    
        all_product=1
        include_flag=0
        for num in nums:
            if num==0:
                include_flag+=1
                continue
            all_product=num*all_product
        record=[]
        for num in nums:
            if include_flag>1:
                record.append(0)
            elif include_flag==1:
                if num==0:
                    record.append(all_product)
                else:
                    record.append(0) 
            elif include_flag==0:
                record.append(all_product/num)
        return record
        

Solution: https://leetcode.com/problems/product-of-array-except-self/