Java Array Program · A38
Three Sum: Triplets That Add to Zero in Java
Sort the array. Fix the first value, then look for the other two with pointers moving in from both ends. Skipping equal values removes duplicate triplets.
Problem Statement
Given an array of integers, return every unique triplet of values from different positions whose sum is zero.
Each triplet is written in ascending order, and the list of triplets is sorted. The same triplet must not appear twice.
Input/Output Examples
[-4, 1, 3, -1, 0, 2, -2]Output[[-4, 1, 3], [-2, -1, 3], [-2, 0, 2], [-1, 0, 1]]Explanation: four different combinations.[0, 0, 0, 0]Output[[0, 0, 0]]Explanation: the triplet is reported once.[1, 2, -4]Output[]Explanation: 1 + 2 - 4 = -1.Visual Explanation
- Sortedarray-4-2-10123fix -4
- Pointerspair-23-4 - 2 + 3 = -3 < 0 move lo right
- …pair13-4 + 1 + 3 = 0 record [-4, 1, 3]
- Next fixed values-2, -1, 0, … give three more
- Done4 triplets
Because the array is sorted, the pointers can only move in one direction each, so every fixed value costs one linear scan. Skipping equal fixed values and equal pointer values prevents duplicates.
Approaches
Sorting plus two pointers is the standard quadratic solution. The brute force tries every triple.
Approach 1: Sort and Two Pointers (Recommended)
Idea: sort; for each fixed index, find pairs in the rest that sum to its negative using two pointers.
- Sort a copy of the array.
- Skip a fixed value equal to the previous one.
- Move
loup if the sum is too small andhidown if too large. - On a match, record it and skip equal values on both sides.
Time: O(n²) · Space: O(n). For the sorted copy.
Approach 2: Every Triple
Idea: check every combination of three positions and store sorted matches in an ordered set.
- Loop over all
i < j < k. - If the three values sum to zero, sort them and add them to the set.
- Return the set as a list.
Time: O(n³) · Space: O(t). t is the number of triplets.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Sort and Two Pointers (Recommended)
The sorted order makes duplicate skipping a matter of comparing neighbours.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThreeSumPointers {
// Fix the smallest value, then find the other two with two pointers; skip equal values
static List<List<Integer>> threeSum(int[] arr) {
int[] a = arr.clone();
Arrays.sort(a);
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < a.length - 2; i++) {
if (i > 0 && a[i] == a[i - 1]) {
continue; // same first value: same triplets
}
int lo = i + 1;
int hi = a.length - 1;
while (lo < hi) {
int sum = a[i] + a[lo] + a[hi];
if (sum < 0) {
lo++;
} else if (sum > 0) {
hi--;
} else {
result.add(List.of(a[i], a[lo], a[hi]));
while (lo < hi && a[lo] == a[lo + 1]) {
lo++;
}
while (lo < hi && a[hi] == a[hi - 1]) {
hi--;
}
lo++;
hi--;
}
}
}
return result;
}
public static void main(String[] args) {
int[][] inputs = {{-4, 1, 3, -1, 0, 2, -2}, {0, 0, 0, 0}, {1, 2, -4}};
for (int[] arr : inputs) {
System.out.println(Arrays.toString(arr) + " -> " + threeSum(arr));
}
}
}
[-4, 1, 3, -1, 0, 2, -2] -> [[-4, 1, 3], [-2, -1, 3], [-2, 0, 2], [-1, 0, 1]] [0, 0, 0, 0] -> [[0, 0, 0]] [1, 2, -4] -> []
Time complexity: O(n²) · Space complexity: O(n).
Approach 2: Every Triple
Cubic, but it is an independent check of the two-pointer logic.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class ThreeSumBrute {
// Tries every triple of positions, storing sorted triplets in a set to remove repeats: O(n^3)
static List<List<Integer>> threeSum(int[] arr) {
TreeSet<List<Integer>> found = new TreeSet<>((x, y) -> {
for (int k = 0; k < 3; k++) {
if (!x.get(k).equals(y.get(k))) {
return x.get(k) - y.get(k);
}
}
return 0;
});
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
for (int k = j + 1; k < arr.length; k++) {
if (arr[i] + arr[j] + arr[k] == 0) {
int[] t = {arr[i], arr[j], arr[k]};
Arrays.sort(t);
found.add(List.of(t[0], t[1], t[2]));
}
}
}
}
return new ArrayList<>(found);
}
public static void main(String[] args) {
int[][] inputs = {{-4, 1, 3, -1, 0, 2, -2}, {0, 0, 0, 0}, {1, 2, -4}};
for (int[] arr : inputs) {
System.out.println(Arrays.toString(arr) + " -> " + threeSum(arr));
}
}
}
[-4, 1, 3, -1, 0, 2, -2] -> [[-4, 1, 3], [-2, -1, 3], [-2, 0, 2], [-1, 0, 1]] [0, 0, 0, 0] -> [[0, 0, 0]] [1, 2, -4] -> []
Time complexity: O(n³) · Space complexity: O(t).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Sort and Two Pointers | O(n²) | O(n) |
| Every Triple | O(n³) | O(t) |
Here n is the number of elements. Sorting costs O(n log n), and each fixed value needs one linear pointer scan, so the total is O(n²).
Interview Tips and Recommended Approach
- Skip duplicates in three places: the fixed value, the left pointer and the right pointer.
- Stop early. Once the fixed value is positive, no later triplet can sum to zero.
- Reduce to two-sum. Explaining the problem that way shows the structure.
- Know the generalisation: k-sum adds one loop per extra element.
Recommended Approach: Sort and Two Pointers
Why: it is the expected O(n²) answer, and sorting makes both the search and the duplicate handling simple.