Skip to content

Instantly share code, notes, and snippets.

@alexitaylor
Last active May 25, 2017 16:48
Show Gist options
  • Save alexitaylor/41fca528b2e60297b48b7238ce419573 to your computer and use it in GitHub Desktop.
Save alexitaylor/41fca528b2e60297b48b7238ce419573 to your computer and use it in GitHub Desktop.
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without division and in O(n). For example, given [1,2,3,4], return [24,12,8,6].
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
var result = [];
var right = 1;
var left = 1;
for (var j = 0; j <= nums.length - 1; j++) {
result[j] = left;
left *= nums[j];
}
for (var i = nums.length - 1; i >= 0; i--) {
result[i] *= right;
right *= nums[i];
}
return result;
};
// Runtime: 212 ms
// Solved in O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment