Three Sum in Java: Explanation & Practice
Find all unique triplets that sum to zero
Problem summary
Given an array, find all unique triplets [a, b, c] such that a + b + c = 0. Combine sorting with two pointers for an efficient solution.
Starter code
public class Main {
public static void main(String[] args) {
int[] nums = {-1, 0, 1, 2, -1, -4};
// 1. Sort the array
// 2. Fix one element, use two pointers for remaining
// 3. Skip duplicates
// Print each triplet on new line: -1 -1 2
}
}Expected output and test cases
- [-1,0,1,2,-1,-4]
-1 -1 2 -1 0 1
- [0,0,0]
0 0 0
- [-2,0,1,1,2]
-2 0 2 -2 1 1
Hints
- Sort array first to enable two-pointer technique
- For each element nums[i], find two elements that sum to -nums[i]
- Skip duplicate values to avoid duplicate triplets
- After finding a triplet, skip all duplicates for both pointers
Related Data Structures & Algorithms exercises
- Practice Remove Duplicates from Sorted Array in Java
- Practice Container With Most Water in Java
- Practice Valid Palindrome in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler