Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to find the unique triplet that is close to the given target using C#?
The Three Sum Closest problem asks us to find a triplet of numbers in an array whose sum is closest to a given target value. This problem uses the Two Pointers pattern and is similar to the Triplet Sum to Zero problem.
We iterate through the array, taking one number at a time as the first element of our triplet. For each fixed element, we use two pointers to find the best pair that makes the triplet sum closest to the target. At every step, we save the difference between the triplet sum and the target, comparing it with the minimum difference found so far.
Algorithm Steps
Sort the array to enable the two-pointer technique.
Initialize the closest sum with the first triplet.
Iterate through each element as the first element of the triplet.
Use two pointers (left and right) to find the optimal pair for the remaining elements.
Update the closest sum whenever we find a triplet closer to the target.
Example
using System;
using System.Linq;
public class Arrays {
public int ThreeSumClosest(int[] num, int target) {
if (num == null || num.Length < 3) {
return -1;
}
int[] nums = num.OrderBy(x => x).ToArray();
int closestSum = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.Length - 2; i++) {
int left = i + 1;
int right = nums.Length - 1;
while (left < right) {
int currentSum = nums[i] + nums[left] + nums[right];
if (Math.Abs(currentSum - target) < Math.Abs(closestSum - target)) {
closestSum = currentSum;
}
if (currentSum == target) {
return currentSum;
}
else if (currentSum < target) {
left++;
}
else {
right--;
}
}
}
return closestSum;
}
}
class Program {
static void Main(string[] args) {
Arrays solution = new Arrays();
int[] nums = { -1, 2, 1, -4 };
int target = 1;
Console.WriteLine("Array: [{0}]", string.Join(", ", nums));
Console.WriteLine("Target: " + target);
Console.WriteLine("Closest sum: " + solution.ThreeSumClosest(nums, target));
// Test with another example
int[] nums2 = { 1, 1, 1, 0 };
int target2 = -100;
Console.WriteLine("\nArray: [{0}]", string.Join(", ", nums2));
Console.WriteLine("Target: " + target2);
Console.WriteLine("Closest sum: " + solution.ThreeSumClosest(nums2, target2));
}
}
The output of the above code is −
Array: [-1, 2, 1, -4] Target: 1 Closest sum: 2 Array: [1, 1, 1, 0] Target: -100 Closest sum: 2
How It Works
The algorithm works by first sorting the array, then for each element as the first number of the triplet, it uses two pointers to efficiently find the pair that creates the sum closest to the target. When the current sum is less than the target, we move the left pointer right to increase the sum. When it's greater, we move the right pointer left to decrease the sum.
Time and Space Complexity
| Complexity | Value | Explanation |
|---|---|---|
| Time Complexity | O(N²) | Sorting takes O(N log N), the nested loop takes O(N²) |
| Space Complexity | O(N) | Required for sorting the array |
Conclusion
The Three Sum Closest problem efficiently finds the triplet with sum nearest to a target using the two-pointer technique on a sorted array. This approach reduces the time complexity from O(N³) brute force to O(N²), making it suitable for larger datasets.
