How to find the unique triplet that is close to the given target using C#?


Two Pointers pattern and is similar to Triplet Sum to Zero. We can follow a similar approach to iterate through the array, taking one number at a time. At every step, we will save the difference between the triplet and the target number, and at each step we will compare it with the minimum target difference so far, so that in the end, we can return the triplet with the closest sum.

Time complexity

Sorting the array will take O(N* logN). Overall threeSumClosest() will take O(N * logN + N^2), which is asymptotically equivalent to O(N^2).

Space complexity

The space complexity of the above algorithm will be O(N) which is required for sorting.

Example

public class Arrays{
   public int ThreeSumClosest(int[] num, int target){
      if (num == null || num.Length == 0){
         return -1;
      }
      int[] nums = num.OrderBy(x => x).ToArray();
      int initialclosest = nums[0] + nums[1] + nums[2];
      for (int i = 0; i < nums.Count(); i++){
         int left = i + 1;
         int right = nums.Length - 1;
         while (left < right){
            int newClosest = nums[i] + nums[left] + nums[right];
            if (Math.Abs(newClosest - target) < Math.Abs(initialclosest - target)){
               initialclosest = newClosest;
            }
            if (newClosest == target){
               return newClosest;
            }
            else if (newClosest < target){
               left++;
            }
            else
            {
               right--;
            }
         }
      }
      return initialclosest;
   }
}

static void Main(string[] args){
   Arrays s = new Arrays();
   int[] nums = { -1, 2, 1, -4 };
   Console.WriteLine(s.ThreeSumClosest(nums, 1));
}

Output

2

Updated on: 17-Aug-2021

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements