Returns a new array such that each index has the product of all elements except itself.
[1,2,3,4] → [24,12,8,6]
# ✖️ 5. Product of Array Except Self (prefix/suffix method)
# Returns a new array such that each index has the product of all elements except itself.
# Does not use division — builds prefix and suffix products in two passes.
#
# Time Complexity: O(n)
# # Why: Two passes through the array — one forward, one backward — both linear.
def product_except_self(nums)
n = nums.length
res = Array.new(n, 1)
prefix = 1
(0...n).each do |i|
res[i] = prefix
prefix *= nums[i]
end
suffix = 1
(n - 1).downto(0) do |i|
res[i] *= suffix
suffix *= nums[i]
end
res
O(n)
O(1)