Product of array except self
Tue Oct 01 2024 20:13:18 GMT+0000 (Coordinated Universal Time)
Saved by
@kanatov
function productExceptSelf(nums: number[]): number[] {
const postfix = [];
const indexLast = nums.length - 1;
postfix[indexLast] = nums[indexLast];
for (let i = indexLast - 1; i >= 0; i--) {
postfix[i] = postfix[i+1] * nums[i];
}
const result = [postfix[1]];
let prefix = nums[0];
for (let i = 1; i < indexLast; i++) {
result[i] = prefix * postfix[i+1];
prefix *= nums[i]
}
result[indexLast] = prefix;
return result;
};
content_copyCOPY
Comments