views:

151

answers:

3

Hello,

Can you please help me solving this one?

You have an unordered array X of n integers. Find the array M containing n elements where Mi is the product of all integers in X except for Xi. You may not use division. You can use extra memory. (Hint: There are solutions faster than O(n^2).)

The basic ones - O(n^2) and one using division is easy. But I just can't get another solution that is faster than O(n^2).

+4  A: 

Let left[i] be the product of all elements in X from 1..i. Let right[i] be the product of all elements in X from i..N. You can compute both in O(n) without division in the following way: left[i] = left[i - 1] * X[i] and right[i] = right[i + 1] * X[i];

Now we will compute M: M[i] = left[i - 1] * right[i + 1]

Note: left and right are arrays.

Hope it is clear:)

Petar Minchev
You could perhaps add that `left` and `right` are meant to be arrays.
Svante
@Svante OK, I will add that:)
Petar Minchev
Hi Petar. I'm having difficulty understanding your solution. Could you please explain a little bit more?
ebae
@ebae Hi! You want M[i] to be the product of all elements in X except the i-th element. So let `left[i]` = the product of all elements in X with indices < i and `right[i]` = the product of all elements in X with indices > i. Then M[i] = left[i] * right[i]. I have described above how to precompute the `left` and `right` arrays in linear time.
Petar Minchev
+1  A: 

Here's a solution in Python. I did the easy way with division to compare against the hard way without. Do I get the job?

L = [2, 1, 3, 5, 4]

prod = 1
for i in L: prod *= i
easy = map(lambda x: prod/x, L)
print easy

hard = [1]*len(L)
hmm = 1
for i in range(len(L) - 1):
    hmm *= L[i]
    hard[i + 1] *= hmm
huh = 1
for i in range(len(L) - 1, 0, -1):
    huh *= L[i]
    hard[i - 1] *= huh
print hard
xscott