Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created October 31, 2024 12:16
Show Gist options
  • Save sAVItar02/19b166c188cace65068cbf9f0388a7c8 to your computer and use it in GitHub Desktop.
Save sAVItar02/19b166c188cace65068cbf9f0388a7c8 to your computer and use it in GitHub Desktop.
Product of array except self
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
let prefix = 1;
let postfix = 1;
let res = [];
for(let i=0; i<nums.length; i++) {
res[i] = prefix;
prefix = prefix * nums[i];
}
for(let i=nums.length - 1; i>=0; i--) {
res[i] = res[i] * postfix;
postfix = postfix * nums[i];
}
return res;
};
// run a loop to calculate prefix product and add them to the result array
// run another loop from behind and calculate postfix and multiply it with the current stored prefix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment