Add more explanation

This commit is contained in:
Vitor Oliveira 2021-02-28 13:17:09 -08:00
parent 11328ae839
commit c829dd4896

View file

@ -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 = []