From 7e74eced2ead9fde8d02bde895a3c0d5f579253f Mon Sep 17 00:00:00 2001
From: MITHILESH <mkumar199861@gmail.com>
Date: Thu, 1 Oct 2020 12:49:46 +0530
Subject: [PATCH] Create 3-Sum.cpp

---
 cpp/3-Sum.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 47 insertions(+)
 create mode 100644 cpp/3-Sum.cpp

diff --git a/cpp/3-Sum.cpp b/cpp/3-Sum.cpp
new file mode 100644
index 0000000000..1c99b34de1
--- /dev/null
+++ b/cpp/3-Sum.cpp
@@ -0,0 +1,47 @@
+class Solution {
+public:
+    vector<vector<int>> threeSum(vector<int>& nums) {
+   
+        //
+        vector<vector<int>> res;
+        //sort
+        sort(nums.begin(),nums.end());
+        
+        for(unsigned int i = 0; i < nums.size();i++){
+             // initialize left and right 
+           //to handle duplicates
+            if(i > 0 && nums[i]==nums[i-1])
+                continue;
+             int l = i + 1; 
+            int r = nums.size() - 1; 
+            int x = nums[i]; 
+            
+            while (l < r) 
+            {    
+                if (x + nums[l] + nums[r] == 0) {
+                    res.push_back(vector<int>{x,nums[l],nums[r]});
+                    //to handle duplicates
+                    while (l<r && nums[l] == nums[l+1]) 
+                        l++;
+                    // to handle duplicates
+                    while (l<r && nums[r] == nums[r-1]) 
+                        r--;
+                    l++;
+                    r--;
+                    //break;
+                }
+                // If sum of three elements is less 
+                // than zero then increment in left 
+                else if (x + nums[l] + nums[r] < 0) 
+                    l++; 
+  
+                // if sum is greater than zero than 
+                // decrement in right side 
+                else
+                    r--; 
+            }
+                
+        }
+        return res;
+    }
+};