|
| 1 | +/** |
| 2 | + * @param {number[]} nums Array of integers. |
| 3 | + * @return {number[]} Array where each element is a product of all elements except of self. |
| 4 | + * @summary Product of Array Except Self {@link https://leetcode.com/problems/product-of-array-except-self/} |
| 5 | + * @description For a list of integers, return a list where output[i] is a product of all except of input[i]. |
| 6 | + * Space O(n) - It's O(n) if not counting the answer array of nums.length elements. |
| 7 | + * Time O(n) - Two loops each of nums.length steps to calculate the sum. |
| 8 | + */ |
| 9 | +const productExceptSelf = nums => { |
| 10 | + const length = nums.length; |
| 11 | + const answer = Array(length); |
| 12 | + answer[0] = 1; |
| 13 | + let right = 1; |
| 14 | + let i; |
| 15 | + |
| 16 | + for (i = 1; i < length; i++) answer[i] = nums[i - 1] * answer[i - 1]; |
| 17 | + for (i = length - 1; i >= 0; i--) { |
| 18 | + answer[i] = answer[i] * right; |
| 19 | + right = right * nums[i]; |
| 20 | + } |
| 21 | + |
| 22 | + return answer; |
| 23 | +}; |
0 commit comments