Skip to content

Commit 788607c

Browse files
committed
Add week 3 solutions: product-of-array-except-self
1 parent 65ce8e5 commit 788607c

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* https://leetcode.com/problems/product-of-array-except-self
3+
* time complexity : O(n)
4+
* space complexity : O(1)
5+
*/
6+
function productExceptSelf(nums: number[]): number[] {
7+
const n = nums.length;
8+
const answer = new Array(n).fill(1);
9+
10+
let leftProduct = 1;
11+
for (let i = 0; i < n; i++) {
12+
answer[i] = leftProduct;
13+
leftProduct *= nums[i];
14+
}
15+
16+
let rightProduct = 1;
17+
for (let i = n - 1; i >= 0; i--) {
18+
answer[i] *= rightProduct;
19+
rightProduct *= nums[i];
20+
}
21+
22+
return answer;
23+
}

0 commit comments

Comments
 (0)