Problem Statement

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != ji != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

Example 2:

Input: nums = []
Output: []

Example 3:

Input: nums = [0]
Output: []

Constraints:

Problem Link

3Sum - LeetCode

Code

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        
        int n = nums.size();
        sort(nums.begin(),nums.end());
        vector<vector<int>> res;
        
        for(int i=0;i<n;)
        {
            int l = i+1;
            int r = n-1;
            int sum = -nums[i];
            
            while(l<r)
            {
                if(nums[l]+nums[r]==sum)
                {
                    res.push_back({nums[i],nums[l],nums[r]});
                    
                    while(l+1<n&&nums[l]==nums[l+1])
                        l++;
                    l++;
                    
                    while(r-1>=0&&nums[r]==nums[r-1])
                        r--;
                    r--;
                }
                
                else if(nums[l]+nums[r]>sum)
                {
                    while(r-1>=0&&nums[r]==nums[r-1])
                        r--;
                    r--;
                }
                else
                {
                    while(l+1<n&&nums[l]==nums[l+1])
                        l++;
                    l++;
                }
            }
            
            while(i+1<n&&nums[i]==nums[i+1])
                        i++;
                    i++;
        }
        
        return res;
        
    }
};