Skip to content

Commit 5badd68

Browse files
committed
solve: Week 02 product of array except self
1 parent 63ec433 commit 5badd68

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
function productExceptSelf(nums: number[]): number[] {
2+
// Check if there are zeros in the array
3+
const zeroCount = nums.reduce((acc, num) => {
4+
if (num === 0) {
5+
return acc + 1;
6+
} else {
7+
return acc;
8+
}
9+
}, 0);
10+
11+
if (zeroCount === 0) {
12+
// If there are no zeros, calculate the product of all numbers
13+
const totalProduct = nums.reduce((acc, num) => num * acc, 1);
14+
return nums.map((num) => {
15+
return totalProduct / num;
16+
});
17+
} else if (zeroCount === 1) {
18+
// If there is one zero, calculate the product of all numbers except the zero
19+
const totalProduct = nums.reduce((acc, num) => {
20+
if (num === 0) {
21+
return acc;
22+
} else {
23+
return num * acc;
24+
}
25+
}, 1);
26+
return nums.map((num) => {
27+
if (num === 0) {
28+
return totalProduct
29+
} else {
30+
return 0;
31+
}
32+
});
33+
} else {
34+
// If there are more than one zero, return an array of zeros
35+
return nums.map((_) => 0);
36+
}
37+
};

0 commit comments

Comments
 (0)