forked from super30admin/Array-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProductArray.java
More file actions
30 lines (27 loc) · 801 Bytes
/
Copy pathProductArray.java
File metadata and controls
30 lines (27 loc) · 801 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
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// Three line explanation of solution in plain english
/**
* running product without extra space.
* since output array is not extra space,
* we will use the same array for calculating running product from left first
* then reuse the same array for calculating running product from right
*/
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int [] res = new int[n];
int rp =1;
for (int i = 0; i< n; i++){
res[i] = rp;
rp *= nums[i];
}
rp =1;
for (int j = n-1; j>=0; j--){
res[j] = res[j] * rp;
rp *= nums[j];
}
return res;
}
}