Medium
3Sum
- Time limit
- 2 s
- Memory limit
- 256 MB
- Estimated
- 20 min
- Two Pointers
Description
Description
Given an integer array nums, return all unique triplets [a, b, c] such that a + b + c == 0. A triplet uses three distinct positions of nums, but the same value may appear in more than one triplet if it occurs multiple times in the array.
Each returned triplet must have its three values sorted in non-decreasing order, and the overall list of triplets must be sorted lexicographically (compare the first value, then the second, then the third). No duplicate triplets may appear in the output.
Examples
Example 1
- Input:
nums = [-1, 0, 1, 2, -1, -4] - Output:
[[-1, -1, 2], [-1, 0, 1]]
Example 2
- Input:
nums = [0, 1, 1] - Output:
[]
Example 3
- Input:
nums = [0, 0, 0] - Output:
[[0, 0, 0]]
Expected Function Behavior
Constraints
0 <= nums.length <= 3000-100000 <= nums[i] <= 100000
Sample cases
3Sample 1
Input
nums = [-1,0,1,2,-1,-4]
Expected output
[[-1,-1,2],[-1,0,1]]
Sample 2
Input
nums = [0,1,1]
Expected output
[]
Skills and languages
Patterns
- K-Sum Reduction
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer