forked from super30admin/Array-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProduct.java
More file actions
37 lines (27 loc) · 1014 Bytes
/
Copy pathProduct.java
File metadata and controls
37 lines (27 loc) · 1014 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Three line explanation of solution in plain english
/*Calculate the product on the left of all the numbers in the array.
Going from right to left calculate the product on the right of the number and multiply with the product obtained before at each position
*/
// Your code here along with comments explaining your approach
/*
## Problem 1 - Leetcode 238.Product of Array Except Self
*/
class Product {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
int[] leftProduct = new int[nums.length];
result[0] = 1;
for (int i = 1; i < nums.length; i++) {
result[i] = result[i - 1] * nums[i - 1];
}
int rightProduct = 1;
for (int i = nums.length - 2; i >= 0; i--) {
rightProduct *= nums[i + 1];
result[i] = result[i] * rightProduct;
}
return result;
}
}