Created
October 31, 2024 12:16
-
-
Save sAVItar02/19b166c188cace65068cbf9f0388a7c8 to your computer and use it in GitHub Desktop.
Product of array except self
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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