File tree 1 file changed +37
-0
lines changed
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/product-of-array-except-self
2
+ // T: O(N)
3
+ // S: O(1)
4
+
5
+ public class ProductOfArrayExceptItself {
6
+
7
+ private record ProductDetails (int nonZeroProduct , int numberOfZeros ) { }
8
+
9
+ public int [] productExceptSelf (int [] nums ) {
10
+ final ProductDetails productDetails = getProductDetails (nums );
11
+ if (productDetails .numberOfZeros > 1 ) return new int [nums .length ];
12
+ if (productDetails .numberOfZeros == 1 ) return productSumOnlyWhenZero (nums , productDetails .nonZeroProduct );
13
+ final int [] result = new int [nums .length ];
14
+ for (int i = 0 ; i < result .length ; i ++) {
15
+ result [i ] = productDetails .nonZeroProduct / nums [i ];
16
+ }
17
+ return result ;
18
+ }
19
+
20
+ private int [] productSumOnlyWhenZero (int [] array , int product ) {
21
+ final int [] result = new int [array .length ];
22
+ for (int i = 0 ; i < array .length ; i ++) {
23
+ if (array [i ] == 0 ) result [i ] = product ;
24
+ }
25
+ return result ;
26
+ }
27
+
28
+ private ProductDetails getProductDetails (int [] array ) {
29
+ int numberOfZeros = 0 ;
30
+ int nonZeroProduct = 1 ;
31
+ for (int element : array ) {
32
+ if (element == 0 ) numberOfZeros ++;
33
+ else nonZeroProduct *= element ;
34
+ }
35
+ return new ProductDetails (nonZeroProduct , numberOfZeros );
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments