How to find all unique triplets that adds up to sum Zero using C#?

The three-sum problem involves finding all unique triplets in an array that sum to zero. This is a classic algorithmic challenge that can be solved efficiently using a two-pointer technique after sorting the array.

Problem Statement

Given an array of integers, find all unique triplets where nums[i] + nums[j] + nums[k] = 0. The solution must avoid duplicate triplets.

Approach 1: Brute Force

The simplest approach uses three nested loops to check every possible combination of three elements −

  • Time Complexity − O(n³)

  • Space Complexity − O(1)

Approach 2: Optimized Two-Pointer Technique

A more efficient approach sorts the array first, then uses a fixed element with two pointers to find the remaining pair. This reduces time complexity significantly −

  • Time Complexity − O(n²)

  • Space Complexity − O(1) excluding output space

Two-Pointer Strategy i L R Fixed Left Right If sum < 0: move L right, If sum > 0: move R left Skip duplicates to ensure unique triplets

Algorithm Steps

  1. Sort the array in ascending order

  2. Fix the first element and use two pointers for the remaining elements

  3. If sum equals zero, add triplet to result and skip duplicates

  4. If sum is less than zero, move left pointer right

  5. If sum is greater than zero, move right pointer left

Example

using System;
using System.Collections.Generic;
using System.Linq;

public class ThreeSumSolver {
    public List<List<int>> ThreeSum(int[] nums) {
        List<List<int>> result = new List<List<int>>();
        if (nums == null || nums.Length < 3) {
            return result;
        }
        
        Array.Sort(nums);
        
        for (int i = 0; i < nums.Length - 2; i++) {
            // Skip duplicates for the first element
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            
            int left = i + 1;
            int right = nums.Length - 1;
            
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                
                if (sum == 0) {
                    result.Add(new List<int> { nums[i], nums[left], nums[right] });
                    
                    // Skip duplicates for left pointer
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    // Skip duplicates for right pointer
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    left++;
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        
        return result;
    }
    
    public static void Main(string[] args) {
        ThreeSumSolver solver = new ThreeSumSolver();
        int[] nums = { -1, 0, 1, 2, -1, -4 };
        
        Console.WriteLine("Input array: [" + string.Join(", ", nums) + "]");
        var triplets = solver.ThreeSum(nums);
        
        Console.WriteLine("Unique triplets that sum to zero:");
        foreach (var triplet in triplets) {
            Console.WriteLine("[" + string.Join(", ", triplet) + "]");
        }
    }
}

The output of the above code is −

Input array: [-1, 0, 1, 2, -1, -4]
Unique triplets that sum to zero:
[-1, -1, 2]
[-1, 0, 1]

How the Algorithm Works

For the input array [-1, 0, 1, 2, -1, -4], the algorithm follows these steps −

  1. Sort: [-4, -1, -1, 0, 1, 2]

  2. Fix -4: No valid triplet found (sum would be negative)

  3. Fix -1: Find [-1, -1, 2] and [-1, 0, 1]

  4. Skip duplicate -1 and continue

  5. Fix 0: No new unique triplets found

Time and Space Complexity

Approach Time Complexity Space Complexity
Brute Force (3 nested loops) O(n³) O(1)
Two-Pointer Technique O(n²) O(1)
HashSet Approach O(n²) O(n)

Conclusion

The two-pointer technique provides an optimal solution for finding unique triplets that sum to zero with O(n²) time complexity. The key insight is sorting the array first and using two pointers to efficiently search for valid pairs while avoiding duplicates through careful pointer management.

Updated on: 2026-03-17T07:04:36+05:30

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements