Three Sum Problem All Unique Triplets in DSA C# - Time & Space Complexity
We want to understand how the time needed grows when finding all unique triplets that sum to zero in an array.
How does the number of steps change as the array gets bigger?
Analyze the time complexity of the following code snippet.
public IList> ThreeSum(int[] nums) {
Array.Sort(nums);
var result = new List>();
for (int i = 0; i < nums.Length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = nums.Length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.Add(new List{nums[i], nums[left], nums[right]});
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++; right--;
} else if (sum < 0) left++;
else right--;
}
}
return result;
}
This code finds all unique triplets in the array that add up to zero by sorting and using two pointers.
- Primary operation: The outer loop runs through each element, and inside it, a two-pointer while loop scans the remaining elements.
- How many times: Outer loop runs about n times; inner while loop runs up to n times for each outer iteration.
As the array size grows, the number of steps grows roughly with the square of the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 steps |
| 100 | About 10,000 steps |
| 1000 | About 1,000,000 steps |
Pattern observation: The steps increase very fast as input grows, roughly by n times n, which is quadratic growth.
Time Complexity: O(n²)
This means the time needed grows roughly with the square of the input size, so doubling the input makes the work about four times bigger.
[X] Wrong: "The time complexity is O(n³) because there are three nested loops."
[OK] Correct: The inner two-pointer loop moves inward without restarting fully each time, so it runs in total about n times per outer loop, not n² times, making the total O(n²).
Understanding this time complexity helps you explain how to handle problems with multiple loops efficiently and shows you can analyze nested loops carefully.
"What if the input array was already sorted? How would that affect the time complexity?"
Practice
Three Sum Problem All Unique Triplets in an integer array?Solution
Step 1: Understand the problem statement
The problem asks to find all unique groups of three numbers (triplets) in the array whose sum equals zero.Step 2: Clarify the output requirement
We must return all such triplets without duplicates, not just count or sort.Final Answer:
Find all unique triplets that sum to zero -> Option AQuick Check:
Goal = unique triplets summing to zero [OK]
- Confusing triplets with pairs
- Trying to find max sum instead of zero sum
- Ignoring uniqueness of triplets
nums for the Three Sum problem?Solution
Step 1: Check array initialization syntax in C#
Correct syntax for array initialization is:int[] nums = new int[] { ... };Step 2: Validate each option
int[] nums = new int[] { -1, 0, 1, 2, -1, -4 }; uses correct syntax. int nums = { -1, 0, 1, 2, -1, -4 }; misses array type. int[] nums = (-1, 0, 1, 2, -1, -4); uses parentheses instead of braces. int[] nums = new List<int> { -1, 0, 1, 2, -1, -4 }; tries to assign a List to an array variable.Final Answer:
int[] nums = new int[] { -1, 0, 1, 2, -1, -4 }; -> Option CQuick Check:
Array init syntax = int[] nums = new int[] { -1, 0, 1, 2, -1, -4 }; [OK]
- Using parentheses instead of braces
- Assigning List to array variable
- Missing type declaration
int[] nums = { -1, 0, 1, 2, -1, -4 };
var result = ThreeSum(nums);
foreach(var triplet in result) {
Console.WriteLine(string.Join(", ", triplet));
}
// Assume ThreeSum returns List of unique tripletsSolution
Step 1: Sort and find triplets summing to zero
Sorted array: [-4, -1, -1, 0, 1, 2]. Triplets summing to zero are [-1, -1, 2] and [-1, 0, 1].Step 2: Match output with options
[-1, 0, 1] [-1, -1, 2] lists these two triplets correctly. Others contain invalid or impossible triplets.Final Answer:
[-1, 0, 1] [-1, -1, 2] -> Option BQuick Check:
Unique triplets = [-1, 0, 1] [-1, -1, 2] [OK]
- Not sorting before searching
- Including duplicate triplets
- Wrong triplet sums
public IList ThreeSum(int[] nums) {
var result = new List();
Array.Sort(nums);
for (int i = 0; i < nums.Length - 2; i++) {
int left = i + 1, 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] });
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}Solution
Step 1: Analyze duplicate handling in loops
The code does not skip duplicate values for i, left, or right, which can cause duplicate triplets in the result.Step 2: Verify other parts
Array is sorted, sum calculation is correct, and List usage is valid. So only duplicate skipping is missing.Final Answer:
No check to skip duplicate values for i, left, and right -> Option AQuick Check:
Missing duplicate skip = No check to skip duplicate values for i, left, and right [OK]
- Not skipping duplicates causing repeated triplets
- Forgetting to sort array
- Wrong sum calculation
nums = [-2, 0, 1, 2, -1, -1, 2], which of the following lists contains all unique triplets that sum to zero?Solution
Step 1: Sort the array and find triplets
Sorted nums: [-2, -1, -1, 0, 1, 2, 2]. Valid unique triplets summing to zero are [-2, 0, 2], [-1, -1, 2], and [-1, 0, 1].Step 2: Compare with options
[[-2, 0, 2], [-1, -1, 2], [-1, 0, 1]] matches these triplets exactly. Others contain invalid or duplicate triplets.Final Answer:
[[-2, 0, 2], [-1, -1, 2], [-1, 0, 1]] -> Option DQuick Check:
All unique triplets = [[-2, 0, 2], [-1, -1, 2], [-1, 0, 1]] [OK]
- Including triplets with wrong sums
- Missing duplicates in output
- Ignoring sorting step
Ready to prove it?
Pass the test and this pattern moves unknown
