File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments