File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments