Certainly! The Three Sum problem involves finding all unique triplets in an array that sum up to zero. To efficiently solve this problem in C#, we'll follow these steps:
- Sort the Array: Sorting helps in easily avoiding duplicates and efficiently using the two-pointer technique.
- Iterate Through the Array: For each number, we'll use two pointers to find the other two numbers that sum up to the negative of the current number.
- Avoid Duplicates: Skip over duplicate numbers to ensure that each triplet is unique.
Here's the complete C# implementation along with the test cases provided:
using System;
using System.Collections.Generic;
public class ThreeSumSolution
{
public static List<List<int>> ThreeSum(int[] nums)
{
List<List<int>> result = new List<List<int>>();
if (nums == null || nums.Length < 3)
return result;
// Sort the array to make it easier to avoid duplicates and use two pointers
Array.Sort(nums);
for (int i = 0; i < nums.Length - 2; i++)
{
// Skip duplicate elements to avoid duplicate triplets
if (i > 0 && nums[i] == nums[i - 1])
continue;
int left = i + 1;
int right = nums.Length - 1;
while (left < right)
{
int currentSum = nums[i] + nums[left] + nums[right];
if (currentSum == 0)
{
// Found a triplet
result.Add(new List<int> { nums[i], nums[left], nums[right] });
left++;
right--;
// Skip duplicates for the second number
while (left < right && nums[left] == nums[left - 1])
left++;
// Skip duplicates for the third number
while (left < right && nums[right] == nums[right + 1])
right--;
}
else if (currentSum < 0)
{
// Need a larger sum
left++;
}
else
{
// Need a smaller sum
right--;
}
}
}
return result;
}
// Helper method to print the list of triplets
public static void PrintTriplets(List<List<int>> triplets)
{
if (triplets.Count == 0)
{
Console.WriteLine("{ }");
return;
}
Console.Write("{ ");
for (int i = 0; i < triplets.Count; i++)
{
Console.Write("{ ");
for (int j = 0; j < triplets[i].Count; j++)
{
Console.Write(triplets[i][j]);
if (j < triplets[i].Count - 1)
Console.Write(", ");
}
Console.Write(" }");
if (i < triplets.Count - 1)
Console.Write(", ");
}
Console.WriteLine(" }");
}
// Test cases
public static void Main(string[] args)
{
var test1 = new int[] { 0, 1, -1, -1, 2 };
var result1 = ThreeSum(test1);
Console.Write("ThreeSum(new int[] { 0, 1, -1, -1, 2 }) ➞ ");
PrintTriplets(result1);
var test2 = new int[] { 0, 0, 0, 5, -5 };
var result2 = ThreeSum(test2);
Console.Write("ThreeSum(new int[] { 0, 0, 0, 5, -5 }) ➞ ");
PrintTriplets(result2);
var test3 = new int[] { 1, 2, 3 };
var result3 = ThreeSum(test3);
Console.Write("ThreeSum(new int[] { 1, 2, 3 }) ➞ ");
PrintTriplets(result3);
var test4 = new int[] { 10 };
var result4 = ThreeSum(test4);
Console.Write("ThreeSum(new int[] { 10 }) ➞ ");
PrintTriplets(result4);
}
}
Explanation of the Code:
-
Sorting the Array:
Array.Sort(nums); sorts the input array in ascending order. This helps in easily skipping duplicates and using two pointers effectively.
-
Iterating Through the Array:
- The
for loop runs from the start of the array to the third-last element.
- For each
nums[i], we set two pointers: left (immediately after i) and right (at the end of the array).
-
Two-Pointer Technique:
- Calculate the
currentSum of the three numbers.
- If
currentSum is zero, we've found a valid triplet. We add it to the result list.
- Move both pointers to look for the next possible triplet, ensuring we skip over any duplicates.
- If
currentSum is less than zero, increment left to increase the sum.
- If
currentSum is greater than zero, decrement right to decrease the sum.
-
Avoiding Duplicates:
- Before processing a new
i, check if it's a duplicate of the previous number. If so, skip it.
- After finding a valid triplet, skip over any duplicate numbers for both
left and right pointers to ensure uniqueness.
-
Handling Edge Cases:
- If the input array has fewer than three elements, return an empty list.
- If no triplets sum up to zero, return an empty list.
-
Printing the Results:
- The
PrintTriplets method formats and prints the list of triplets for easier readability.
Running the Test Cases:
When you run the Main method, it will execute the four provided test cases and output the results as follows:
ThreeSum(new int[] { 0, 1, -1, -1, 2 }) ➞ { { -1, -1, 2 }, { -1, 0, 1 } }
ThreeSum(new int[] { 0, 0, 0, 5, -5 }) ➞ { { -5, 0, 5 }, { 0, 0, 0 } }
ThreeSum(new int[] { 1, 2, 3 }) ➞ { }
ThreeSum(new int[] { 10 }) ➞ { }
Notes:
- The triplets are sorted in ascending order within each triplet and the list of triplets is also ordered based on the first element of each triplet.
- Duplicate triplets are avoided by skipping over the same elements after a triplet is found.
- The solution has a time complexity of O(n²), which is efficient for this problem.
Feel free to integrate this function into your project or modify it further based on your specific requirements!