From ecde337d9bab5665169c161f88345e0230a25226 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sat, 19 Dec 2020 20:18:22 -0800 Subject: [PATCH] Add better solution - O(n) time and space --- .../get_products_of_all_other_elements.rb | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/data_structures/arrays/get_products_of_all_other_elements.rb b/data_structures/arrays/get_products_of_all_other_elements.rb index 8bfe4a6..b4a8a2f 100644 --- a/data_structures/arrays/get_products_of_all_other_elements.rb +++ b/data_structures/arrays/get_products_of_all_other_elements.rb @@ -21,3 +21,65 @@ def calculate_products_of_all_other_elements(nums) end puts(calculate_products_of_all_other_elements([1, 2, 3])) + +# 2. O(n) time and space +# Arrays - Get Products of all other elements in Ruby + +# Generates prefix products +def build_prefix_products(nums) + prefix_products = [] + + nums.each do |num| + if prefix_products.count > 0 + prefix_products << (prefix_products.last * num) + else + prefix_products << num + end + end + + return prefix_products +end + +# Generates suffix products +def build_suffix_products(nums) + suffix_products = [] + + nums.reverse.each do |num| + if suffix_products.count > 0 + suffix_products << (suffix_products.last * num) + else + suffix_products << num + end + end + + return suffix_products +end + +# Builds output +def output(prefix_products, suffix_products, nums) + result = [] + + nums.reverse.each_with_index do |num, index| + if index == 0 + result << suffix_products[index + 1] + elsif index == nums.length - 1 + result << prefix_products[index - 1] + else + result << (prefix_products[index - 1] * suffix_products[index + 1]) + end + end + + return result +end + +# Generate result from the product of prefixes and suffixes +def products(nums) + prefix_products = build_prefix_products(nums) + suffix_products = build_suffix_products(nums) + suffix_products = suffix_products.reverse + + return output(prefix_products, suffix_products, nums) +end + +puts(products([1, 2, 3])) +# => [6, 3, 2]