1
+ /*
2
+ This code uses prefix and postfix product to evaluate answer.
3
+ We just need to traverse the array twice, once to the left and once to the right.
4
+ Then answer of ith place can be calculated using constant time.
5
+
6
+ Time Complexity : O(n)
7
+ Space Complexity : O(n)
8
+ */
9
+
10
+
11
+
12
+ class Solution {
13
+ public:
14
+ vector<int> productExceptSelf(vector<int>& nums) {
15
+ int n = nums.size(); //Variable for size of the array
16
+ //pre[] stores product of all numbers to the left of ith element
17
+ //post[] stores product of all numbers to the right of ith element
18
+ int pre[n],post[n];
19
+
20
+ //loop to assign values to pre[]
21
+ int mul=1;
22
+ for(int i=0; i<n; i++){
23
+ mul*=nums[i];
24
+ pre[i]=mul;
25
+ }
26
+
27
+ //loop to assign values to post[]
28
+ mul=1;
29
+ for(int i=n-1; i>=0; i--){
30
+ mul*=nums[i];
31
+ post[i]=mul;
32
+ }
33
+
34
+ //declare a vector to return
35
+ vector <int> out;
36
+
37
+ //first element of out is just going to be product of all elements except first one
38
+ out.push_back(post[1]);
39
+
40
+ //value of out[i] = product of all elements except ith element
41
+ //which is nothing but pre[i-1]*[post[i+1]]
42
+ for(int i=1; i<n-1; i++){
43
+ int p=i-1;
44
+ int s=i+1;
45
+ out.push_back(pre[p]*post[s]);
46
+ }
47
+
48
+ //last element of out is just going to be product of all elements except last one
49
+ out.push_back(pre[n-2]);
50
+
51
+ //return the vector
52
+ return out;
53
+ }
54
+ };
0 commit comments