Skip to content

Commit 3161ca5

Browse files
committed
Product of Array Except Self solution
1 parent 5b79511 commit 3161ca5

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* [Problem]: [238] Product of Array Except Self
3+
* (https://leetcode.com/problems/product-of-array-except-self/description/)
4+
*/
5+
6+
function productExceptSelf(nums: number[]): number[] {
7+
// 시간 복잡도 O(n^2)
8+
// 공간 복잡도 O(n)
9+
// 시간 초과로 실패
10+
function doubleLoopFunc(nums: number[]): number[] {
11+
return nums.map((_, i) => nums.reduce((acc, cur, j) => (i === j ? acc : acc * cur), 1));
12+
}
13+
14+
// 시간 복잡도 O(n)
15+
// 공간 복잡도 O(n)
16+
function separateFunc(nums: number[]): number[] {
17+
const length = nums.length;
18+
const result: number[] = new Array(length).fill(1);
19+
let leftProduct = 1;
20+
let rightProduct = 1;
21+
22+
for (let i = 0; i < length; i++) {
23+
result[i] = leftProduct;
24+
leftProduct *= nums[i];
25+
}
26+
27+
for (let i = length - 1; i >= 0; i--) {
28+
result[i] *= rightProduct;
29+
rightProduct *= nums[i];
30+
}
31+
32+
return result;
33+
}
34+
35+
return separateFunc(nums);
36+
}

0 commit comments

Comments
 (0)