DEV Community

SalahElhossiny
SalahElhossiny

Posted on

3 2

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay