-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathProductOfArrayExceptSelf.java
More file actions
32 lines (27 loc) · 924 Bytes
/
ProductOfArrayExceptSelf.java
File metadata and controls
32 lines (27 loc) · 924 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
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// Three line explanation of solution in plain english
/*
compute left pass and right pass products by using single resultant array by considering running product
except the index of the current element and then eventually multiply the results of both these passes to
get the overall product.
*/
class Solution {
public int[] productExceptSelf(int[] nums) {
int len = nums.length;
int[] productArr = new int[len];
int product = 1;
productArr[0] = 1;
for(int i = 1 ; i < len ; i++) {
product = product * nums[i - 1];
productArr[i] = product;
}
product = 1;
for(int i = len - 2 ; i >= 0 ; i--) {
product = product * nums[i + 1];
productArr[i] *= product;
}
return productArr;
}
}