Skip to content

Commit 3a13ac3

Browse files
committed
Add solution of ProductOfArrayExceptSelf task
1 parent fb4f7d7 commit 3a13ac3

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package by.andd3dfx.numeric;
2+
3+
/**
4+
* <pre>
5+
* <a href="https://leetcode.com/problems/product-of-array-except-self/description/">Task description</a>
6+
*
7+
* Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
8+
*
9+
* The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
10+
*
11+
* You must write an algorithm that runs in O(n) time and without using the division operation.
12+
*
13+
* Example 1:
14+
* Input: nums = [1,2,3,4]
15+
* Output: [24,12,8,6]
16+
*
17+
* Example 2:
18+
* Input: nums = [-1,1,0,-3,3]
19+
* Output: [0,0,9,0,0]
20+
* </pre>
21+
*/
22+
public class ProductOfArrayExceptSelf {
23+
24+
public static int[] productExceptSelf(int[] nums) {
25+
var n = nums.length;
26+
var left = new int[n];
27+
var right = new int[n];
28+
29+
left[0] = nums[0];
30+
for (int i = 1; i < n; i++) {
31+
left[i] = left[i - 1] * nums[i];
32+
}
33+
34+
right[n - 1] = nums[n - 1];
35+
for (int i = n - 2; i >= 0; i--) {
36+
right[i] = right[i + 1] * nums[i];
37+
}
38+
39+
nums[0] = right[1];
40+
nums[n - 1] = left[n - 2];
41+
for (int i = 1; i < n - 1; i++) {
42+
nums[i] = left[i - 1] * right[i + 1];
43+
}
44+
return nums;
45+
}
46+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package by.andd3dfx.numeric;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.Test;
6+
7+
public class ProductOfArrayExceptSelfTest {
8+
9+
@Test
10+
public void productExceptSelf() {
11+
assertThat(ProductOfArrayExceptSelf.productExceptSelf(new int[]{0, 0, 0}))
12+
.isEqualTo(new int[]{0, 0, 0});
13+
assertThat(ProductOfArrayExceptSelf.productExceptSelf(new int[]{1, 1, 1, 1}))
14+
.isEqualTo(new int[]{1, 1, 1, 1});
15+
16+
assertThat(ProductOfArrayExceptSelf.productExceptSelf(new int[]{1, 2, 3, 4}))
17+
.isEqualTo(new int[]{24, 12, 8, 6});
18+
assertThat(ProductOfArrayExceptSelf.productExceptSelf(new int[]{-1, 1, 0, -3, 3}))
19+
.isEqualTo(new int[]{0, 0, 9, 0, 0});
20+
}
21+
}

0 commit comments

Comments
 (0)