-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathLeetcode238.java
More file actions
21 lines (20 loc) · 845 Bytes
/
Leetcode238.java
File metadata and controls
21 lines (20 loc) · 845 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// SC - O(1) since no extra space is being used
// TC - O(n) Iteration of the array twice.
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
int suffixMul = nums[nums.length - 1];
int prefixMul = 1;
res[0] = prefixMul;
for (int i = 1; i < nums.length; i++) {
res[i] = nums[i - 1] * prefixMul; // res[i] will contain Mul till i-1
prefixMul = res[i]; // prefix mul 0 to i
}
for (int i = nums.length - 2; i >= 0; i--) {
res[i] = res[i] * suffixMul;// res[i] will contain Mul till i-1 and multiplied by suffix -> product of all
// items except ith element
suffixMul = nums[i] * suffixMul; // suffix mul from i to n
}
return res;
}
}