Skip to content

Commit 46c2c84

Browse files
Create 238-Product-of-Array-Except-Self.java
1 parent c482529 commit 46c2c84

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//Just store the left and right product (Try doing this with extra space first)
2+
//This one is constant space because we are returning the array we created
3+
4+
class Solution {
5+
public int[] productExceptSelf(int[] nums) {
6+
int[] arr = new int[nums.length];
7+
arr[0] = 1;
8+
for (int i = 1; i<nums.length; i++) {
9+
arr[i] = arr[i-1]*nums[i-1];
10+
}
11+
int prod = nums[nums.length-1];
12+
nums[nums.length-1] = 1;
13+
for (int i = nums.length-2; i>=0; i--) {
14+
int store = nums[i];
15+
nums[i] = nums[i+1]*prod;
16+
prod = store;
17+
}
18+
for (int i = 0; i<nums.length; i++) {
19+
arr[i] = arr[i]*nums[i];
20+
}
21+
return arr;
22+
}
23+
}

0 commit comments

Comments
 (0)