DEV Community

SalahElhossiny
SalahElhossiny

Posted on

Leetcode Solutions: Product of Array Except Self

Here is the text of problem:

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Here is my different solution:


class Solution(object):
    def productExceptSelf(self, nums):

        p = 1

        zeroCount = 0

        if all([num == 0 for num in nums]):
            return nums

        for num in nums:
            if num == 0:
                zeroCount += 1
                continue
            p *= num 

        p = p if zeroCount < 2 else 0

        res = []

        includeZero = 0 in nums

        for num in nums:
            if num == 0:
                res.append(p)

            elif includeZero:
                res.append(0)
            elif num != 0:
                res.append(p/num)


        return res

Enter fullscreen mode Exit fullscreen mode

Discussion (0)