Skip to content

Commit 957565a

Browse files
authored
Add files via upload
1 parent c8f5e8d commit 957565a

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

ProductArray.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.util.Arrays;
2+
3+
public class ProductArray {
4+
5+
//we do left to right product and store previous elements product in current index
6+
//we need to do product from right and multiply with current value
7+
//O(n)
8+
//[1 2 3 4 5]
9+
//[1 1 1*2 1*2*3 1*2*3*4]
10+
//[*2*3*4*5 *3*4*5 *4*5 *5 *1 ]
11+
public static int[] productExceptSelf(int[] nums) {
12+
int[] res=new int[nums.length];
13+
res[0]=1;
14+
//left to right product
15+
for(int i=1;i<nums.length;i++) {
16+
res[i]=res[i-1]*nums[i-1];
17+
}
18+
19+
int pro=1;
20+
//right to left product
21+
for(int i=nums.length-1;i>=0;i--) {
22+
res[i]*=pro;
23+
pro*=nums[i];
24+
}
25+
return res;
26+
}
27+
28+
public static void main(String[] args) {
29+
System.out.println("120,60,40,30,24 Expected " );
30+
Arrays.stream(productExceptSelf(new int[]{1,2,3,4,5})).forEach(x->System.out.print(x+" "));
31+
}
32+
}

0 commit comments

Comments
 (0)