File tree Expand file tree Collapse file tree
product-of-array-except-self Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .Arrays ;
2+
3+ class Solution {
4+ // TC : O(n)
5+ // SC : O(n)
6+ public int [] productExceptSelf (int [] nums ) {
7+ /**
8+ * Approach:
9+ * 1. Calculate the product of all non-zero elements
10+ * 2. Count how many zeros exist in the array.
11+ * 3. Handle three cases:
12+ * - If there are more than one zero, all results are 0.
13+ * - If there is exactly one zero,
14+ * only the index with 0 gets the total product; others are 0.
15+ * - If there is no zero, each result is totalProduct / nums[i].
16+ */
17+ int zeroCount = 0 ;
18+
19+ for (int n : nums ) {
20+ if (n == 0 ) {
21+ zeroCount ++;
22+ }
23+ if (zeroCount > 1 ) {
24+ break ;
25+ }
26+ }
27+
28+ if (zeroCount > 1 ) {
29+ return new int [nums .length ];
30+ }
31+
32+ int production = Arrays .stream (nums ).filter ((n ) -> {
33+ return n != 0 ;
34+ }).reduce (1 , (a , b ) -> a * b );
35+
36+ if (zeroCount == 1 ) {
37+ return Arrays .stream (nums ).map ((n ) -> {
38+ if (n == 0 ) {
39+ return production ;
40+ }
41+ return 0 ;
42+ }).toArray ();
43+ }
44+
45+ return Arrays .stream (nums ).map ((n ) -> {
46+ return production / n ;
47+ }).toArray ();
48+ }
49+ }
You canโt perform that action at this time.
0 commit comments