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

  1. Sort array first to enable two-pointer technique
  2. For each element nums[i], find two elements that sum to -nums[i]
  3. Skip duplicate values to avoid duplicate triplets
  4. After finding a triplet, skip all duplicates for both pointers

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler