Problem
Given an array nums
of n integers where n > 1, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
**Note: **Please solve it without division and in O(n).
Follow up: Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
Solution 1
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
var len = nums.length;
var left = Array(len + 1);
var right = Array(len + 1);
var res = Array(len);
left[0] = 1;
right[0] = 1;
for (var i = 0; i < len; i++) {
left[i + 1] = left[i] * nums[i];
}
for (var j = 0; j < len; j++) {
right[j + 1] = right[j] * nums[len - 1 - j];
}
for (var k = 0; k < len; k++) {
res[k] = left[k] * right[len - k - 1];
}
return res;
};
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).
Solution 2
/**
* @param {number[]} nums
* @return {number[]}
*/
var productExceptSelf = function(nums) {
var len = nums.length;
var res = Array(len);
var right = 1;
res[0] = 1;
for (var i = 1; i < len; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
for (var j = len - 1; j >= 0; j--) {
res[j] *= right;
right *= nums[j];
}
return res;
};
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(1).