Two Pointers
3-Sum
DESCRIPTION (inspired by Leetcode.com)
Given an input integer array nums, write a function to find all unique triplets [nums[i], nums[j], nums[k]] such that i, j, and k are distinct indices, and the sum of nums[i], nums[j], and nums[k] equals zero. Ensure that the resulting list does not contain any duplicate triplets.
Input:
nums = [-1,0,1,2,-1,-1]
Output:
[[-1,-1,2],[-1,0,1]]
Explanation: Both nums[0], nums[1], nums[2] and nums[1], nums[2], nums[4] both include [-1, 0, 1] and sum to 0. nums[0], nums[3], nums[4] ([-1,-1,2]) also sum to 0.
Since we are looking for unique triplets, we can ignore the duplicate [-1, 0, 1] triplet and return [[-1, -1, 2], [-1, 0, 1]].
The order of the triplets and the order of the elements within the triplets do not matter.
Solution
Explanation
Result
Avoiding Duplicates
Avoiding Duplicates II
Termination
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n²) where n is the length of the input array. This is due to the nested loops in the algorithm. We perform n iterations of the outer loop, and each iteration takes O(n) time to use the two-pointer technique.
Space Complexity: O(n²) where n is the length of the input array. We need to store all distinct triplets that sum to 0, which can be at most O(n²) triplets.
Your account is free and you can post anonymously if you choose.