// Computes product of array except self.
// nums = input array
// returns a new array containing the result
function productExceptSelf(nums) {
const size = nums.length;
const answer = new Array(size).fill(1);
// ---- Prefix products ----
// answer[i] gets product of all elements before i
let prefix = 1;
for (let i = 0; i < size; i++) {
answer[i] = prefix; // store prefix product
prefix *= nums[i]; // update prefix
// Example for nums = [5,2,3,4]:
// prefix values: 1, 5, 10, 30
}
// ---- Suffix products ----
// Multiply each answer[i] by product of all elements after i
let suffix = 1;
for (let i = size - 1; i >= 0; i--) {
answer[i] *= suffix; // combine prefix * suffix
suffix *= nums[i]; // update suffix
// suffix values: 1, 4, 12, 24, 120
// final answer: 24, 60, 40, 30
// 24 (24*1) 60 (12*5) 40 (10*4) 30 (30*1)
}
return answer;
}
// Main program
const arr = [5, 2, 3, 4];
const result = productExceptSelf(arr);
process.stdout.write("Result: ");
for (const x of result) {
process.stdout.write(x + " ");
}
/*
run:
Result: 24 60 40 30
*/