📘
Three Sum
MediumTwo Pointers
Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, j != k, and nums[i] + nums[j] + nums[k] == 0.
The solution set must not contain duplicate triplets. Output each triplet sorted, one per line, with triplets sorted lexicographically.
Example:
Input:
-1,0,1,2,-1,-4
Output:
-1 -1 2 -1 0 1
Reasoning:
- The input array
numsis first sorted to apply the two-pointer technique: [−4,−1,−1,0,1,2]. - We iterate over the array and for each element, we use two pointers, one starting from the next element and one from the end, to find a pair that sums to −nums[i].
- For nums[0]=−4, no triplet sums to 0, but for nums[1]=−1, we find −1+0+1=0 and for nums[2]=−1, we find −1+−1+2=0.
- These two unique triplets [−1,0,1] and [−1,−1,2] are then sorted and output, resulting in the given sample output.
Constraints:
- 3 <= len(nums) <= 3000
- -10^5 <= nums[i] <= 10^5
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.