Skip to content

Instantly share code, notes, and snippets.

@sharunkumar
Last active March 27, 2023 22:19
Show Gist options
  • Save sharunkumar/baba81d0cfa62acfb23a8e300dab6dd4 to your computer and use it in GitHub Desktop.
Save sharunkumar/baba81d0cfa62acfb23a8e300dab6dd4 to your computer and use it in GitHub Desktop.
238. Product of Array Except Self
# https://leetcode.com/problems/product-of-array-except-self/description/
# Runtime 219 ms Beats 96.61% Memory 21.1 MB Beats 95.12%
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
zeroes = set()
prod = 1
for i, x in enumerate(nums):
if x == 0:
zeroes.add(i)
else:
prod *= x
array = []
if len(zeroes) == 1:
array = [prod if i in zeroes else 0 for i, x in enumerate(nums)]
elif len(zeroes) > 1:
array = [0 for i in nums]
else:
array = [prod // i for i in nums]
return array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment