forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path238.cpp
More file actions
28 lines (20 loc) · 722 Bytes
/
238.cpp
File metadata and controls
28 lines (20 loc) · 722 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
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size(), i, prodSoFar = 1;
vector<int> output(n, nums[n - 1]);
//preprocessing the array
for (i = n - 2; i >= 0; i--){
output[i] = output[i + 1] * nums[i];
}
for (i = 0; i < n - 1; i++){
output[i] = prodSoFar * output[i + 1];
prodSoFar *= nums[i];
}
output[n - 1] = prodSoFar;
return output;
}
};
//==============================================================
//Time complexity of the above algorithm: O(n), n is the length of the input array
//Space complexity: O(1), constant space