File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 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+ };
Original file line number Diff line number Diff line change @@ -147,6 +147,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
147147| 1512 | [ Number of Good Pairs] ( https://leetcode.com/problems/number-of-good-pairs/ ) | [ Java] ( ./Java/Number-of-Good-Pairs.java ) | O(N^2) | O(1) | Easy | Array |
148148| 162 | [ Find Peak element] ( https://leetcode.com/problems/find-peak-element/ ) | [ javascript] ( https://github.com/codedecks-in/LeetCode-Solutions/blob/master/JavaScript/findPeakElement.js ) | o(Logn) | O(1) | Medium | Array |
149149| 54 | [ Spiral Matrix] ( https://leetcode.com/problems/spiral-matrix/ ) | [ C++] ( ./C++/Spiral-matrix.cpp ) | O(M\* N) | O(M\* N) | Medium | Array |
150+ | 238 | [ Product of Array Except Self] ( https://leetcode.com/problems/product-of-array-except-self/ ) | [ C++] ( ./C++/238.Product_of_array_except_self ) | O(N) | O(N) | Medium | Array |
150151
151152
152153<br />
You can’t perform that action at this time.
0 commit comments