complexity theory - Get an O(N) algorithm to find a product of a collection of numbers with a strange constraint -
this question when participated recent interview, think interesting. let's int n=10;
input : array int a[10];
output: array float b[10];
requirement:
b[0]= a[1]*a[2]*...a[9]; // product of numbers in a, other a[0]; b[1]= a[0]*a[2]*...a[9]; // product of numbers in a, other a[1]; .... b[9]= a[0]*a[1]*...a[8]; // product of numbers in a, other a[9]; ....
problem: how can array b
populated without using division operator /
? , o(n)
algorithm?
i tried quite few methods, still in vain. ideas?
firstly, calculate left , right products:
left[i] = a[0]*a[1]*...*a[i] right[i] = a[i]*a[i+1]*...*a[n-1]
note left[i] == left[i-1] * a[i]
, left
array can computed in linear time. simlarly, right
array can computed in linear time.
from left
, right
, array b
can computed in linear time b[i] = left[i-1] * right[i+1]
special cases i == 0
, i == n
.
Comments
Post a Comment