Last active
May 25, 2017 16:48
-
-
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].
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) { | |
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