Skip to content

Commit aae15b9

Browse files
committed
product of array expect self solution
1 parent 36e83e6 commit aae15b9

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/*
2+
time complexity : O(n)
3+
space complexity : O(1)
4+
*/
5+
function productExceptSelf(nums: number[]): number[] {
6+
const results = new Array(nums.length).fill(1)
7+
let before = 1
8+
let after = 1
9+
for (let i = 0; i < nums.length - 1; i++) {
10+
before *= nums[i]
11+
results[i + 1] *= before
12+
}
13+
for (let i = nums.length - 1; i > 0; i--) {
14+
after *= nums[i]
15+
results[i - 1] *= after
16+
}
17+
18+
return results
19+
};

0 commit comments

Comments
 (0)