Three Sum

#include <bits/stdc++.h>
using namespace std;

// https://leetcode.com/problems/3sum/

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

Notice that the solution set must not contain duplicate triplets.

//fix one variable and apply two pointer on rest.
vector<vector<int>> threeSum(vector<int>& nums) {
    vector<vector<int>> ans;
    
    if(nums.size() < 3return ans;
    
    sort(nums.begin(), nums.end());            
    
    set<vector<int>> triplet;
    
    for(int i=0;i<=nums.size()-3;i++){            
        //two pointer:
        int p = i+1;
        int q = nums.size()-1;

        
        while(p < q){
            if(nums[p] + nums[q] + nums[i] == 0){
                triplet.insert({nums[i], nums[p], nums[q]});
                p++;q--;
            }
            
            else if(nums[p] + nums[q] + nums[i] < 0) p++;
            else q--;
            
        }     
        
    }
    
    //ans push:
        for(auto t: triplet) ans.push_back(t);   
    
    return ans;
    
}

void main(){

}

Comments

Popular Posts