Product of Array Except Self [Solution]
Here’s a Python implementation of the product_except_self
function:
from typing import List
def product_except_self(nums: List[int]) -> List[int]:
"""
Return an array where each element is the product of all the elements in the input array except itself.
Parameters:
- nums: List of integers.
Returns:
- List[int]: Array of products.
"""
n = len(nums)
# Initialize output array with all elements set to 1
output = [1] * n
# Calculate products of elements to the left of each element
left_product = 1
for i in range(n):
output[i] *= left_product
left_product *= nums[i]
# Calculate products of elements to the right of each element
right_product = 1
for i in range(n - 1, -1, -1):
output[i] *= right_product
right_product *= nums[i]
return output
# Example usage:
nums1 = [1, 2, 3, 4]
result1 = product_except_self(nums1)
print(result1) # Output: [24, 12, 8, 6]
nums2 = [-1, 1, 0, -3, 3]
result2 = product_except_self(nums2)
print(result2) # Output: [0, 0, 9, 0, 0]
nums3 = [0, 0]
result3 = product_except_self(nums3)
print(result3) # Output: [0, 0]
nums4 = [10, 0]
result4 = product_except_self(nums4)
print(result4) # Output: [0, 10]
This solution uses two passes through the array to calculate the products of elements to the left and right of each element efficiently without using division.
Time Complexity:
The time complexity is O(n)
,
where n
is the length of the input array.
Space Complexity:
The space complexity is O(1)
since the output array is not counted in the space complexity.