algorithmdata-structures

Optimal solutions for the practices about data structures from the Algorithm Design Manual


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?


Solution

  • O(n) solution:

    1. Compute array A such that A_i is the product of X_1..X_i
    2. Compute array B such that B_i is the product of X_i..X_n (in reverse, i.e. from array index n)
    3. Then compute M as M_i = A_(i-1)*B_(i+1)

    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

    1. Compute array A as: A_1 = X_1; for i in (2..N): A_i = A_(i-1)*X_i
    2. Compute array B as: B_n = X_n; for i in (N..2): B_i = B_(i+1)*X_i
    3. Compute array M as: M_1 = B_2; M_n = A_(n-1); for i in (2..(N-1)): M_i = A_(i-1)*B_(i+1)