-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproduct_of_array_except_self.cpp
More file actions
83 lines (68 loc) · 2.12 KB
/
product_of_array_except_self.cpp
File metadata and controls
83 lines (68 loc) · 2.12 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
238. Product of Array Except Self
Time Complexity: O(n)
Space Complexity: O(1) excluding output array
*/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> result(n, 1);
int prefix = 1;
for (int i = 0; i < n; i++) {
result[i] = prefix;
prefix *= nums[i];
}
int suffix = 1;
for (int i = n - 1; i >= 0; i--) {
result[i] *= suffix;
suffix *= nums[i];
}
return result;
}
};
// Helper function to print vector
void printVector(const vector<int>& vec) {
cout << "[";
for (int i = 0; i < vec.size(); i++) {
cout << vec[i];
if (i < vec.size() - 1) cout << ", ";
}
cout << "]" << endl;
}
// Test cases
int main() {
Solution solution;
// Example 1
vector<int> nums1 = {1, 2, 3, 4};
cout << "Example 1: ";
printVector(solution.productExceptSelf(nums1)); // Expected: [24, 12, 8, 6]
// Example 2
vector<int> nums2 = {-1, 1, 0, -3, 3};
cout << "Example 2: ";
printVector(solution.productExceptSelf(nums2)); // Expected: [0, 0, 9, 0, 0]
// Edge case: two elements
vector<int> nums3 = {1, 2};
cout << "Example 3: ";
printVector(solution.productExceptSelf(nums3)); // Expected: [2, 1]
// Edge case: with negative numbers
vector<int> nums4 = {-1, -2, -3, -4};
cout << "Example 4: ";
printVector(solution.productExceptSelf(nums4)); // Expected: [-24, -12, -8, -6]
// Edge case: multiple zeros
vector<int> nums5 = {0, 0, 1};
cout << "Example 5: ";
printVector(solution.productExceptSelf(nums5)); // Expected: [0, 0, 0]
// Edge case: single zero
vector<int> nums6 = {1, 0, 3};
cout << "Example 6: ";
printVector(solution.productExceptSelf(nums6)); // Expected: [0, 3, 0]
// Edge case: all ones
vector<int> nums7 = {1, 1, 1, 1};
cout << "Example 7: ";
printVector(solution.productExceptSelf(nums7)); // Expected: [1, 1, 1, 1]
return 0;
}