Tuesday, December 15, 2015

Products of all numbers in the array

This is google coding interview question:

Given an array of numbers, replace each number with the
product of all the numbers in the array except the number itself *without* using division

https://www.glassdoor.com/Interview/Given-an-array-of-numbers-replace-each-number-with-the-product-of-all-the-numbers-in-the-array-except-the-number-itself-w-QTN_9132.htm

The key to this solution is construct the accessory arrays which assists the solution. Here are the code 


Recursive way

public static int[] products(int[] nums){
int[] products = new int[nums.length];
productRec(nums, products, 0);
return products;
}
public static int productRec(int[] nums, int[] products, int i){
if(i==nums.length-1)
return 1;
products[i] = (i==0?1:products[i-1] * nums[i-1]);
int p = productRec(nums, products, i+1) * nums[i+1];
products[i] = products[i] * p;
return p;
}
view raw productRec.java hosted with ❤ by GitHub

Iterative way:


public static int[] product(int[] nums){
int len = nums.length;
int[] result = new int[len];
result[0] = 1;
for(int i=1; i<len; i++){
result[i] = result[i-1] * nums[i-1];
}
int p = 1;
for(int i=len-2; i>=0; i--){
p = p * nums[i+1];
result[i] = result[i] * p;
}
return result;
}

No comments:

Post a Comment