3Sum
Medium · Two Pointers · Array · Two Pointers · Sorting
Problem
Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] with distinct indices that sum to zero.
The triplets may be returned in any order, and no triplet may be repeated.
Examples
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]]
Two distinct triplets sum to zero; the repeated -1 must not produce a duplicate.
Input: nums = [0,1,1] Output: []
No triplet sums to zero.
Input: nums = [0,0,0] Output: [[0,0,0]]
One triplet, reported once.
Constraints
- 3 <= len(nums) <= 3000
- -10^5 <= nums[i] <= 10^5
Approaches
- Hash set per anchor — time O(n²), space O(n)
Related problems
Start free on Cariara · Coding problems · System design studio