Skip to content

Commit b71c9fa

Browse files
committed
product-of-array-except-self solution
1 parent 245a1b1 commit b71c9fa

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// TC: O(n) / SC: O(n)
2+
var productExceptSelf = function (nums) {
3+
const left = [1];
4+
const right = [1];
5+
const result = [];
6+
7+
for (let i = 1; i < nums.length; i++) {
8+
left.push(left[i - 1] * nums[i - 1]);
9+
}
10+
11+
for (let i = nums.length - 1; i > 0; i--) {
12+
right.push(right[nums.length - 1 - i] * nums[i]);
13+
}
14+
15+
for (let i = 0, j = nums.length - 1; i < nums.length; i++, j--) {
16+
result[i] = left[i] * right[j];
17+
}
18+
19+
return result;
20+
};
21+
22+
// TC: O(n) / SC: O(1)
23+
var productExceptSelf = function (nums) {
24+
const left = new Array(nums.length).fill(1);
25+
26+
for (let i = 1; i < nums.length; i++) {
27+
left[i] = left[i - 1] * nums[i - 1];
28+
}
29+
30+
let rightProduct = 1;
31+
for (let i = nums.length - 1; i >= 0; i--) {
32+
left[i] *= rightProduct;
33+
rightProduct *= nums[i];
34+
}
35+
36+
return left;
37+
};

0 commit comments

Comments
 (0)