Skip to content

Commit 1b74e37

Browse files
authored
Create Leetcode_238.cpp
1 parent 34daed8 commit 1b74e37

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Leetcode_238.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include<iostream>
2+
#include<vector>
3+
using namespace std;
4+
5+
// Function to calculate the product of the array except self
6+
// Time complexity: O(n), Space complexity: O(1) (excluding output vector)
7+
vector<int> productExceptSelf(vector<int>& nums) {
8+
int n = nums.size(); // Size of the input array
9+
vector<int> ans(n, 1); // Initialize result vector with 1 for all elements
10+
int suffix = 1; // Variable to keep track of the suffix product
11+
12+
// First pass: Compute the prefix product for each element
13+
for(int i = 1; i < n; i++) {
14+
ans[i] = ans[i - 1] * nums[i - 1]; // Prefix product for index i
15+
}
16+
17+
// Second pass: Multiply by the suffix product for each element
18+
for(int i = n - 2; i >= 0; i--) {
19+
suffix *= nums[i + 1]; // Update the suffix product
20+
ans[i] *= suffix; // Multiply the prefix product by the suffix product
21+
}
22+
23+
return ans; // Return the resulting vector
24+
}
25+
26+
int main() {
27+
// Input array
28+
vector<int> nums = {1, 2, 3, 4};
29+
30+
// Call the function to compute the result
31+
vector<int> ans = productExceptSelf(nums);
32+
33+
// Display the result
34+
cout << "Product of Array except self is ";
35+
for(int value : ans) {
36+
cout << value << " "; // Print each value in the result
37+
}
38+
39+
return 0; // End of program
40+
}

0 commit comments

Comments
 (0)