3 Sum Leetcode Solution
3 Sum Leetcode Problem :
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.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
3 Sum Leetcode Solution :
Constraints :
- 3<=nums.length<=3000
- -10^5<=nums[i]<=10^5
Example 1:
Input: nums=[0,1,1]
Output: [ ]
Example 2:
Input: nums = [0,0,0]
Output: [[0,0,0]]
In the “3 sum” problem you are given an integer array nums
, the goal is to find all unique triplets within the array such that the sum of the elements in each triplet is equal to zero (i.e.,nums[i] + nums[j] + nums[k] == 0
), and the indices i, j, and k are all distinct (i.e., i != j, i != k, and j != k
).
Here are the key points for the given constraints and examples:
Constraints:
- The length of the nums array is between 3 and 3000.
- The values in the nums array can range from -100,000 to 100,000.
Approach :
For Solving 3 sum sum Leetcode Problem we can use following procedure :
To solve the problem of finding all unique triplets in an integer array nums such that the sum of the elements in each triplet is equal to zero (i.e., nums[i] + nums[j] + nums[k] == 0), you can use a modified version of the “3Sum” algorithm. Here’s the approach:
- Sort the Array: Start by sorting the input array nums in non-decreasing order. Sorting the array will help simplify the problem and allow for an efficient solution.
- Iterate Through the Array: Iterate through the sorted array using a loop. For each element at index i, consider it as a potential first element of the triplet.
- Use Two-Pointers Approach: Inside the loop, use a two-pointers approach to find the other two elements that, when combined with nums[i], sum to zero. Initialize two pointers, left and right, where left points to the element just after nums[i], and right points to the last element in the array.
- Check the Sum:
- Calculate the sum of the current triplet, i.e., nums[i] + nums[left] + nums[right].
- If the sum is equal to zero, you’ve found a valid triplet.
- Add it to the result.
- If the sum is less than zero, increment the left pointer to move towards larger values.
- If the sum is greater than zero, decrement the right pointer to move towards smaller values.
- Avoid Duplicates: To avoid duplicate triplets in the result, ensure that you skip duplicate elements for nums[i], nums[left], and nums[right]. When you find a valid triplet or adjust the pointers, make sure to check for duplicates and skip them.
- Continue Iterating: Continue this process until the i index reaches the third-to-last element in the array. This ensures that you’ve considered all possible first elements of the triplet.
- Return the Result: After completing the loop, return the list of unique triplets that sum to zero.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
#include#include using namespace std; vector > threeSum(vector & nums) { vector > triplets; int n = nums.size(); if (n < 3) { return triplets; // Not enough elements to form a triplet } sort(nums.begin(), nums.end()); // Sort the array in non-decreasing order for (int i = 0; i < n - 2; ++i) { // Skip 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 total = nums[i] + nums[left] + nums[right]; if (total == 0) { triplets.push_back({nums[i], nums[left], nums[right]}); // Skip duplicates for the second element while (left < right && nums[left] == nums[left + 1]) { left++; } // Skip duplicates for the third element while (left < right && nums[right] == nums[right - 1]) { right--; } left++; right--; } else if (total < 0) { left++; } else { right--; } } } return triplets; }
class Solution { public List> threeSum(int[] nums) {
List<List<Integer>> triplets = new ArrayList<>(); int n = nums.length; if (n < 3) { return triplets; // Not enough elements to form a triplet } Arrays.sort(nums); // Sort the array in non-decreasing order for (int i = 0; i < n - 2; ++i) { // Skip 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 total = nums[i] + nums[left] + nums[right]; if (total == 0) { triplets.add(Arrays.asList(nums[i], nums[left], nums[right])); // Skip duplicates for the second element while (left < right && nums[left] == nums[left + 1]) { left++; } // Skip duplicates for the third element while (left < right && nums[right] == nums[right - 1]) { right--; } left++; right--; } else if (total < 0) { left++; } else { right--; } } } return triplets; } }
class Solution(object): def threeSum(self, nums): triplets = [] nums.sort() # Sort the array in non-decreasing order n = len(nums) for i in range(n - 2): # Skip duplicates for the first element if i > 0 and nums[i] == nums[i - 1]: continue left, right = i + 1, n - 1 while left < right: total = nums[i] + nums[left] + nums[right] if total == 0: triplets.append([nums[i], nums[left], nums[right]]) # Skip duplicates for the second element while left < right and nums[left] == nums[left + 1]: left += 1 # Skip duplicates for the third element while left < right and nums[right] == nums[right - 1]: right -= 1 left += 1 right -= 1 elif total < 0: left += 1 else: right -= 1 return triplets
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment