Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Here is the solution in Ruby:
def product_except_self(nums)
n = nums.length
left_products = Array.new(n, 1)
right_products = Array.new(n, 1)
left_product = 1
(1...n).each do |i|
left_product *= nums[i - 1]
left_products[i] = left_product
end
right_product = 1
(n - 2).downto(0).each do |i|
right_product *= nums[i + 1]
right_products[i] = right_product
end
result = Array.new(n)
(0...n).each do |i|
result[i] = left_products[i] * right_products[i]
end
result
end
Here is a step-by-step solution :
1. Initialize Arrays:
left_products = Array.new(n, 1)
right_products = Array.new(n, 1)
Initialize two arrays, left_products and right_products, both filled with 1 and having the length of the input array nums.
2. Calculate Products to the Left:
left_product = 1
(1...n).each do |i|
left_product *= nums[i - 1]
left_products[i] = left_product
end
Iterate through the array nums from index 1 to the end. For each index i, calculate the product of all elements to the left of i and store it in the left_products array.
3. Calculate Products to the Right:
right_product = 1
(n - 2).downto(0).each do |i|
right_product *= nums[i + 1]
right_products[i] = right_product
end
Iterate through the array nums from the second-to-last index to 0. For each index i, calculate the product of all elements to the right of i and store it in the right_products array.
4. Calculate Final Result Array:
result = Array.new(n)
(0...n).each do |i|
result[i] = left_products[i] * right_products[i]
end
5. Return Result:
result
Return the final result array.
In summary, the function calculates the product of all elements except the one at each index in the input array nums using two auxiliary arrays. The time complexity is O(n), and the space complexity is also O(n).