re: Daily Coding Problem #2 VIEW POST

FULL DISCUSSION
 

Here is O(N) without division:

arr = (1..5).to_a
a1, a2 =
  arr.zip(arr.reverse).reduce([[1, 1], [[1], [1]]]) do |((ap, rp), (acc, racc)), (av, rv)|
    [[av, rv], [acc << acc.last*ap, racc << racc.last*rp]]
  end.last.map { |a| a.drop(1) }
a1.zip(a2.reverse).map { |a| a.reduce(:*) }
#⇒ [120, 60, 40, 30, 24]

The idea is to calculate opposite partial products and then reduce them. In a language that has a proper map_reduce function implemented on enumerables (like Elixir,) that might be done in one step without intermediate variables.

code of conduct - report abuse