From c829dd4896423bf2aca3356546f19fff1dccf351 Mon Sep 17 00:00:00 2001 From: Vitor Oliveira Date: Sun, 28 Feb 2021 13:17:09 -0800 Subject: [PATCH] Add more explanation --- .../get_products_of_all_other_elements.rb | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) 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 467ac65..0a46f88 100644 --- a/data_structures/arrays/get_products_of_all_other_elements.rb +++ b/data_structures/arrays/get_products_of_all_other_elements.rb @@ -5,6 +5,11 @@ # each element at index `i` of the new array is the product of # all the numbers in the original array except the one at `i`. +# Generates prefix products +# prefix_products[i] contains the product of all the elements to the left +# Note: for the element at index '0', there are no elements to the left, +# so the prefix_products[0] would be 1 + # # 1. Brute force solution # @@ -23,11 +28,22 @@ end puts(calculate_products_of_all_other_elements([1, 2, 3])) # -# 2. O(n) time and space +# Approach 2: Left and Right product lists # Arrays - Get Products of all other elements in Ruby # +# Complexity analysis +# +# Time complexity: O(N) where N represents the number of elements in the input +# array. We use one iteration to construct the array prefix_products, one to construct +# the array suffix_products and one last to construct the answeranswer array using L and R. +# Space complexity: O(N) used up by the two intermediate arrays that +# we constructed to keep track of product of elements to the left and right. + # Generates prefix products +# prefix_products[i] contains the product of all the elements to the left +# Note: for the element at index '0', there are no elements to the left, +# so the prefix_products[0] would be 1 def build_prefix_products(nums) prefix_products = [] @@ -43,6 +59,9 @@ def build_prefix_products(nums) end # Generates suffix products +# suffix_products[i] contains the product of all the elements to the right +# Note: for the element at index 'length - 1', there are no elements to the right, +# so the suffix_products[length - 1] would be 1 def build_suffix_products(nums) suffix_products = [] @@ -58,6 +77,9 @@ def build_suffix_products(nums) end # Builds output +# For the first element, suffix_products[i] would be product except self +# For the last element of the array, product except self would be prefix_products[i] +# Else, multiple product of all elements to the left and to the right def output(prefix_products, suffix_products, nums) result = []