Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions data_structures/arrays/product_of_array_except_self.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""
Implement and demonstrate the Product of Array Except Self algorithm.

Given an integer list `nums`, return a list `res` such that `res[i]` is equal to
the product of all the elements of `nums` except `nums[i]`, computed in O(n)
time without using division.

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


def product_except_self(nums: list[int]) -> list[int]:
"""
Return a list where each element is the product of all other elements in `nums`.

>>> product_except_self([1, 2, 3, 4])
[24, 12, 8, 6]
>>> product_except_self([-1, 1, 0, -3, 3])
[0, 0, 9, 0, 0]
>>> product_except_self([2, 3])
[3, 2]
>>> product_except_self([0, 0])
[0, 0]
>>> product_except_self([])
[]
"""
n = len(nums)
res = [1] * n

for i in range(1, n):
res[i] = res[i - 1] * nums[i - 1]

suffix = 1
for i in range(n - 1, -1, -1):
res[i] *= suffix
suffix *= nums[i]

return res


def main() -> None:
"""
Demonstrate the product_except_self function.

>>> main()
[24, 12, 8, 6]
"""
print(product_except_self([1, 2, 3, 4]))


if __name__ == "__main__":
main()
Loading