public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums); // Step 1: Sort the array
List<List<Integer>> triplets = new ArrayList<>();
for (int i = 0; i < nums.length; ++i) {
// Step 2: Skip duplicates for the first number
if (i > 0 && nums[i] == nums[i - 1]) continue;
// Step 3: Use two pointers to find remaining pair
int j = i + 1, k = nums.length - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == 0) {
triplets.add(Arrays.asList(nums[i], nums[j], nums[k]));
k--;
// Step 4: Skip duplicates for third number
while (k > 0 && nums[k] == nums[k + 1]) k--;
} else if (sum > 0) {
k--;
while (k > 0 && nums[k] == nums[k + 1]) k--; // Skip duplicates
} else {
j++;
while (j < nums.length && nums[j] == nums[j - 1]) j++; // Skip duplicates
}
}
}
return triplets;
}