-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path238. Product of Array Except Self.java
66 lines (54 loc) · 2.18 KB
/
238. Product of Array Except Self.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Solution {
public int[] productExceptSelf(int[] nums) {
// o(n^2) solution
// loop through all items
// for all items
// loop through all items and multiply them
// o(n) solution that violates constraing
// loop through all items and multiply them
// loop through all items again
// for each item
// answer[i] = product / nums[i]
// o(n) solution
// first go from left side
// then go from right side
// i.e.
// make a prefix product array from the left
// make a prefix product array from the right
// multiply the prefix product arrays
// return solution
// int[] prefixLeft = new int[nums.length];
// int[] prefixRight = new int[nums.length];
// prefixLeft[0] = 1;
// prefixLeft[1] = nums[0];
// prefixRight[nums.length - 1] = 1;
// prefixRight[nums.length - 2] = nums[nums.length - 1];
// for (int i = 2; i < nums.length; i++) {
// prefixLeft[i] = prefixLeft[i - 1] * nums[i - 1];
// }
// for (int i = nums.length - 3; i > -1; i--) {
// prefixRight[i] = prefixRight[i + 1] * nums[i + 1];
// }
// int[] answer = new int[nums.length];
// for (int i = 0; i < nums.length; i++) {
// answer[i] = prefixLeft[i] * prefixRight[i];
// }
// return answer;
// o(n) complexity with o(1) extra space complexity
int[] prefixLeft = new int[nums.length];
int prefixRightRight;
int prefixRight;
prefixLeft[0] = 1;
prefixLeft[1] = nums[0];
prefixRightRight = 1;
for (int i = 2; i < nums.length; i++) {
prefixLeft[i] = prefixLeft[i - 1] * nums[i - 1];
}
for (int i = nums.length - 2; i > -1; i--) {
prefixRight = prefixRightRight * nums[i + 1];
prefixLeft[i] = prefixLeft[i] * prefixRight;
prefixRightRight = prefixRight;
}
return prefixLeft;
}
}