- 🧩 Problem link: Leetcode
- 🚦 Difficulty: 🟡 Medium
Using sorting and the two-pointer technique:
-
Sort the array so that we can efficiently move pointers and handle duplicates.
-
Fix one number (
nums[i]) at a time. -
Use two pointers (
landr) to find pairs whose sum equals-nums[i].- If the sum is zero, we record the triplet.
- If the sum is less than zero, we move
lforward to increase it. - If the sum is greater than zero, we move
rbackward to decrease it.
-
To avoid duplicates, we store results in a
set<vector<int>>.
Finally, we convert the set into a vector and return the unique triplets.
- Time: O(n^2)
- Space:
- O(1) or O(n) extra space depending on the sorting algorithm
- O(m) space for the output list
class Solution
{
public:
vector<vector<int>> threeSum(vector<int> &nums)
{
set<vector<int>> triplets;
vector<vector<int>> res;
sort(nums.begin(), nums.end());
int n = nums.size();
for (int i = 0; i < n; i++)
{
int l = i + 1, r = n - 1;
while (l < r)
{
int currSum = nums[i] + nums[l] + nums[r];
if (currSum == 0)
{
triplets.insert({nums[i], nums[l], nums[r]});
l++;
}
else if (currSum < 0)
{
l++;
}
else
{
r--;
}
}
}
for (auto vec : triplets)
res.push_back(vec);
return res;
}
};