diff --git a/data_structures/arrays/product_of_array_except_self.py b/data_structures/arrays/product_of_array_except_self.py new file mode 100644 index 000000000000..02646c2201b1 --- /dev/null +++ b/data_structures/arrays/product_of_array_except_self.py @@ -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()