Skip to content

Commit 88f6f89

Browse files
committed
add: ProductArrayWithoutCurrentElement
1 parent e0d39ec commit 88f6f89

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import java.util.Arrays;
2+
3+
public class ProductArrayWithoutCurrentElement {
4+
public int[] productArrayWithoutCurrentElement(int[] nums) {
5+
int n = nums.length;
6+
int[] res = new int[n];
7+
Arrays.fill(res, 1);
8+
// Populate the output with the running left product.
9+
for (int i = 1; i < n; i++) {
10+
res[i] = res[i - 1] * nums[i - 1];
11+
}
12+
// Multiply the output with the running right product, from right to
13+
// left.
14+
int rightProduct = 1;
15+
for (int i = n - 1; i > -1; i--) {
16+
res[i] *= rightProduct;
17+
rightProduct *= nums[i];
18+
}
19+
return res;
20+
}
21+
}

0 commit comments

Comments
 (0)