Amazon Interview Question

given non-zero number array A, create array B where B[i] = product of all elements in A except A[i].

Interview Answers

Anonymous

May 25, 2012

You are given an array A of length N. Out of this one array make two more: 1. B, whose n-th element is the product of the first n numbers in A. 2. C, whose n-th element is the product of the last N-n numbers in A. To compute the wanted array D do D[i] = B[i] * C[i+1]. We can construct B, C, and D in linear time so the whole thing is linear.

1

Anonymous

Mar 15, 2012

No division, minimize number of multiplications.

Anonymous

Mar 19, 2012

#include using namespace std; int main() { int A[5] = {1,2,3,4,5}; int B[5] = {1,1,1,1,1}; for (int i = 0; i<5 ; i++) for(int j=0 ; j< 5; j++) { if (i != j) { B[i] *= A[j]; } } for (int k = 0 ; k < 5;k++) { cout<

Anonymous

Mar 25, 2012

That will use n^2 number of multiplications. Using a table with size i,j where i

Anonymous

Mar 27, 2012

The fundamental idea behind this problem is to break it down into smaller pieces and solve those smaller pieces, dynamic programming. So in this case lets consider a list A: A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Notice that B[4], B[5] and B[6] are: B[4] = (A[1]*A[2]*A[3]) * (A[5]*A[6]*A[7]*A[8]*A[9]*A[10]) B[5] = (A[1]*A[2]*A[3]*A[4]) * (A[6]*A[7]*A[8]*A[9]*A[10]) B[6] = (A[1]*A[2]*A[3]*A[4]*A[5]) * (A[7]*A[8]*A[9]*A[10]) So each step is represented as the product of the two numbers. And the component part of these products grow in a known way. So we should be able to do the computation in O(N) time with 2N operations. Here is some code in python. I did this quickly so it might not be the most elegant code but it should demonstrate the idea: a = [1,2,3,4,5,6,7,8,9,10] def cct(i,b) : return str(i) + str(b) def make_key(a): if a: return reduce(cct,a) else: return '' partial_values = {} def pi(a): if not a: return 1; la = len(a) hash_str = make_key(a) if la == 1: partial_values[hash_str] = a[0] return a[0] else: if partial_values.has_key(hash_str): return partial_values[hash_str] else: value = a[0] * pi(a[1:]) partial_values[hash_str] = value return value def f(a): results = [] for i in range(len(a)): beginning = a[0:i] beginning.reverse() end = a[i+1:] results.append( pi(beginning) * pi(end) ) return results