|
| 1 | +# This problem was asked by Uber. |
| 2 | +# |
| 3 | +# Given an array of integers, return a new array such that each element at |
| 4 | +# index i of the new array is the product of all the numbers in the original |
| 5 | +# array except the one at i. |
| 6 | +# |
| 7 | +# For example, if our input was [1, 2, 3, 4, 5], the expected output would be |
| 8 | +# [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would |
| 9 | +# be [2, 3, 6]. |
| 10 | +# |
| 11 | +# Follow-up: what if you can't use division? |
| 12 | +class Problem002 |
| 13 | + # O(n) space and time complexity |
| 14 | + def self.solution(values) |
| 15 | + result, size = [], values.size |
| 16 | + prefix_products = [] |
| 17 | + (0...size).each do |i| |
| 18 | + if prefix_products.empty? |
| 19 | + prefix_products.append(values[i]) |
| 20 | + else |
| 21 | + prefix_products.append(prefix_products[-1] * values[i]) |
| 22 | + end |
| 23 | + end |
| 24 | + suffix_products = [] |
| 25 | + values.reverse.each do |val| |
| 26 | + if suffix_products.empty? |
| 27 | + suffix_products << val |
| 28 | + else |
| 29 | + suffix_products << suffix_products[-1] * val |
| 30 | + end |
| 31 | + end |
| 32 | + suffix_products = suffix_products.reverse |
| 33 | + (0...size).each do |i| |
| 34 | + if(i==0) |
| 35 | + result.append(suffix_products[i + 1]) |
| 36 | + elsif(i == size-1) |
| 37 | + result.append(prefix_products[i - 1]) |
| 38 | + else |
| 39 | + result.append(prefix_products[i-1] * suffix_products[i+1]) |
| 40 | + end |
| 41 | + end |
| 42 | + return result |
| 43 | + end |
| 44 | + |
| 45 | + # O(n^2) time complexity |
| 46 | + def self.solution1(values) |
| 47 | + result, size = [], values.size |
| 48 | + (0...size).each do |i| |
| 49 | + mult = 1 |
| 50 | + (0...size).each do |j| |
| 51 | + unless(i == j) |
| 52 | + mult *= values[j] |
| 53 | + end |
| 54 | + end |
| 55 | + result << mult |
| 56 | + end |
| 57 | + return result |
| 58 | + end |
| 59 | +end |
0 commit comments