Tags: LeetCode DSA Two Pointers
Prompt:
3Sum
MediumTopicsCompany TagsHints
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] where nums[i] + nums[j] + nums[k] == 0, and the indices i, j and k are all distinct.
The output should not contain any duplicate triplets. You may return the output and the triplets in any order.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
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].
Solution:
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
//sort the array first
std::sort(nums.begin(), nums.end());
//the return vector
vector<vector<int>> returnVec;
for(int i = 0; i < nums.size(); i++)
{
if (nums[i] > 0) break; //the array is sorted so there is no way to reach zero
//if a number is the same as the previous number, skip over it
if(i > 0 && nums[i] == nums[i-1]) { continue; }
//otherwise perform the same left right iteration we had in two sum 2:
int left = i+1;
int right = nums.size()-1;
//this value needs to be inversed so we can find two values to add up to it, this way these values plus num[i] will equal 0
int inversedNum = -nums[i];
while(left < right)
{
int outPut = nums[left] + nums[right];
if(outPut == inversedNum)
{
//add the indexes to the return array
returnVec.push_back({nums[i], nums[left], nums[right]});
left++;
right--;
while (left < right && nums[left] == nums[left - 1]) left++;
}
else if(nums[left] + nums[right] > inversedNum)
{
right--;
}
else
{
left++;
}
}
}
return returnVec;
}
};
Explanation
This one is a direct build on of the previous “sum” leetcodes that were done. We are given three distinct values that we need to keep track of, and while the most obvious solution is a brute force o(n^3) solution with a hashset for getting rid of duplicates, there is actually a much easier way that is only o(n^2) with a space complexity of only O(1)
Now the original idea here was to have an index i that would be a value that we should try to set as our target, and then apply the regular 2 sum solution with the hashmap to find whatever two things add up to -i so we get to zero. Doing this does actually work, and it does get you down to o(n^2) time, but once again the issue is duplicates, so a hashset would be needed.
However, there are a few optimizations to this idea above, what we can actually do is the same concept, but getting rid of the hashmap idea of the original 2 sum, and then use the Two Integer Sum (Sorted Input) solution instead! We know we can sort a given array in O(nlog(n)) time, but given that the solution is o(n^2) at the best instance this is fine because n squared grows faster. Except now with a sorted solution, all of the duplicates are next to each other.
So with each new integer, you check to see if it’s previous value was a duplicate, and if so, then you can skip over it. Logically as well, we know we continuously check past the current “i” index, so we will need values that can be the inverse of the current index of i in order to get to zero, so as soon as we pass zero, we know we do not have an answer.
Given this optimization, we can have this fake sum we try to find at the index of i and then we can just use the solution for the two integer sorted input leetcode, and iterate from the left and right down to the middle until we find a solution that is the inverse of i, so that way they will all add up to zero.