I'm practicing algorithms and am doing a problem where you are given an array and you want to return an array with the product of all other numbers except the number at that index. so [1, 2, 3, 4] would return [24, 12, 8, 6]. My approach was to loop through the array, make a copy, and splice out the current index, then push that copy to an output array.
function getAllProductsExceptAtIndex(arr) {
var productArr = [];
for (var i = 0; i < arr.length; i++) {
var copy = arr.slice();
copy.splice(i, 1);
productArr[i] = copy;
}
// return productArr;
for (var j = 0; j < productArr.length; j++) {
reduce(productArr[j]);
}
}
getAllProductsExceptAtIndex([1, 2, 3]); ---> productArr = [[2,3],[1,3],[1,2]]
Now you have an output array with the correct values in it, it just needs to be "reduced" to one value with multiplication. now reduce is groovy and all, but in this case I'm trying to be efficient (time-wise) and so looping through an array and reducing would be o(n) squared since reduce uses a for loop internally. I thought of writing a helper to reduce but if you call it in the loop is it still o(n)squared?
What's a more efficient way to multiply the elements inside each index of productArr, and then flatten? would prefer not to use division in the solution.