→ Values, not indexes, are returned (sorting is allowed)
→ "Unique" → sort and skip duplicates
→ n ≤ 3000 → O(n²) is fine
These clues point to Two Pointers: Opposite Ends: Start one pointer at each end and move them towards each other, using a rule to decide which one moves.
Stuck? Take one hint at a time
Solution.java · starter
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> out = new ArrayList<>();
return out;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Check all triples and store sorted triples in a set to remove duplicates.
Approach 1
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> found = new HashSet<>();
int n = nums.length;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
for (int k = j + 1; k < n; k++)
if (nums[i] + nums[j] + nums[k] == 0) {
List<Integer> t = new ArrayList<>(List.of(nums[i], nums[j], nums[k]));
Collections.sort(t);
found.add(t);
}
return new ArrayList<>(found);
}
}
Verdict: 4.5 × 10⁹ triples at n = 3000: too slow.
2
Optimal: sort + fix one + two pointers
Time O(n²) Space O(1) extra besides the output (sorting aside)
Sort. For each i (skipping values equal to the previous i), run two pointers on i+1..n−1 looking for −nums[i]. On a match, record it, then move L and R past all copies of their values.
If nums[i] > 0, stop: three values that are all at least nums[i] can't sum to 0.