Reputation: 33
This question is from the book The Algorithm Design Manual, 3-28.
The question is:
You have an unordered array X of n integers. Find the array M containing n elements where M_i is the product of all integers in X except for X_i. You may not use division and can use extra memory. (Hint: There exists solution faster than O(n^2).
Anybody has some great ideas?
Upvotes: 3
Views: 277
Reputation: 48366
Just use one array and two loops, one loop is from front to end, the other loop is from back to end.
b[0] = a[1]*a[2]*a[3]*a[4]
b[1] = a[0]* a[2]*a[3]*a[4]
b[2] = a[0]*a[1]* a[3]*a[4]
b[3] = a[0]*a[1]*a[2]* a[4]
b[4] = a[0]*a[1]*a[2]*a[3]
Here are the codes:
void solve(int arr[], int len){
int index = 0;
// loop from begin to end
arr_b[0] = 1;
for (index = 1; index < len; ++index){
arr_b[index] = arr_b[index - 1]*arr_a[index - 1];
}
// loop from end to begin
for (index = len-2; index > 0; --index){
arr_b[0] *= arr_a[index + 1];
arr_b[index] *= arr_b[0];
}
arr_b[0] *= arr_a[1];
}
Upvotes: 0
Reputation: 6235
O(n) solution:
Steps 1 and 2 can be computed in O(n) by using the subproducts computed in previous iterations.
[Of course, handle corner cases where the indices escape array bounds!]
Edit: I'm providing the complete solution below for clarity
Upvotes: 4