We want the result to contain an array where where .
We can use a popular algorithm pattern: prefix and suffix product. Depending on a problem it could be a sum instead of product, or it could just be prefix or suffix alone.
The basic idea is to calculate the increasing cumulative product in an array.
Then finally, we simply iterate over both: prefix and suffix to multiply the previous (i-1) prefix and next (i+1) suffix element.
Code:
Java
Big O Analysis
-
Runtime
The runtime complexity here is
O(N)
. -
Memory
The memory usage is
O(N)
since we use a prefix and suffix arrays of .
— A