Skip to content

Commit 7f1344a

Browse files
committed
Refactor productExceptSelf method to eliminate division
Add missing newline at the end of the file in dohyeon2.java
1 parent e8e6de1 commit 7f1344a

1 file changed

Lines changed: 31 additions & 31 deletions

File tree

product-of-array-except-self/dohyeon2.java

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -5,45 +5,45 @@ class Solution {
55
// SC : O(n)
66
public int[] productExceptSelf(int[] nums) {
77
/**
8+
* I previously solved this problem using division,
9+
* but the problem restricts that approach.
10+
* This was pointed out in the following comment:
11+
* https://github.com/DaleStudy/leetcode-study/pull/2396#discussion_r2934545648
12+
*
813
* 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].
14+
* Compute prefix products using left[i-1] * nums[i-1],
15+
* which represents the product of elements before i.
16+
*
17+
* Compute suffix products using right[i+1] * nums[i+1]
18+
* by traversing from right to left.
19+
*
20+
* The result at index i is:
21+
* left[i] * right[i]
1622
*/
17-
int zeroCount = 0;
1823

19-
for (int n : nums) {
20-
if (n == 0) {
21-
zeroCount++;
22-
}
23-
if (zeroCount > 1) {
24-
break;
25-
}
26-
}
24+
int[] answer = new int[nums.length];
25+
26+
int[] left = new int[nums.length];
27+
Arrays.fill(left, 1);
28+
int[] right = new int[nums.length];
29+
Arrays.fill(right, 1);
2730

28-
if (zeroCount > 1) {
29-
return new int[nums.length];
31+
for (int i = 0; i < nums.length; i++) {
32+
if (i - 1 < 0)
33+
continue;
34+
left[i] *= left[i - 1] * nums[i - 1];
3035
}
3136

32-
int production = Arrays.stream(nums).filter((n) -> {
33-
return n != 0;
34-
}).reduce(1, (a, b) -> a * b);
37+
for (int i = nums.length - 1; i >= 0; i--) {
38+
if (i + 1 > nums.length - 1)
39+
continue;
40+
right[i] *= right[i + 1] * nums[i + 1];
41+
}
3542

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+
for (int i = 0; i < nums.length; i++) {
44+
answer[i] = left[i] * right[i];
4345
}
4446

45-
return Arrays.stream(nums).map((n) -> {
46-
return production / n;
47-
}).toArray();
47+
return answer;
4848
}
4949
}

0 commit comments

Comments
 (0)