Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Three Sum Array Problem in C++ #377

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions Three Sum Array Problem in C++
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
int n = nums.size();

// Sort the array
sort(nums.begin(), nums.end());

// Iterate over the array
for (int i = 0; i < n - 2; ++i) {
// Avoid duplicates for the first element
if (i > 0 && nums[i] == nums[i - 1]) continue;

int left = i + 1;
int right = n - 1;

while (left < right) {
int sum = nums[i] + nums[left] + nums[right];

if (sum == 0) {
result.push_back({nums[i], nums[left], nums[right]});

// Avoid duplicates for the second element
while (left < right && nums[left] == nums[left + 1]) left++;
// Avoid duplicates for the third element
while (left < right && nums[right] == nums[right - 1]) right--;

// Move both pointers inward
left++;
right--;
}
else if (sum < 0) {
left++;
}
else {
right--;
}
}
}

return result;
}

int main() {
vector<int> nums = {-1, 0, 1, 2, -1, -4};

vector<vector<int>> result = threeSum(nums);

// Print the result
cout << "Triplets with sum 0 are:" << endl;
for (auto& triplet : result) {
cout << "[";
for (int i = 0; i < triplet.size(); ++i) {
cout << triplet[i];
if (i < triplet.size() - 1) cout << ", ";
}
cout << "]" << endl;
}

return 0;
}