Three Number Sum [Medium] C#

Three Number Sum [Medium] C#

Time Complexity O(n^2)|O(n) Space Approach: Use a loop through all elements and use two pointer approach(Left and Right) along with this.

Algorithm:

  1. Sort the given array, Declare a triplets list.(List of Int Array)
  2. Start a loop from i = 0 till i < len(arr)- 2 [Since we use two pointers]
  3. Left Pointer = i+1
  4. Right Pointer = len(arr)-1
  5. Loop till Left Pointer < Right Pointer
  6. In every iteration find Current Sum = arr[i] + arr[left] + arr[right]
  7. if CurrentSum == target sum add it to the triplet list and left ++, right --
  8. If CurrentSum < targetSum => left++
  9. If CurrentSum > targetSum => right--
  10. Return triplets list.
using System;
using System.Collections.Generic;
public class Program {
    public static List<int[]> ThreeNumberSum(int[] array, int targetSum) {
        Array.Sort(array);
        List<int[]> tripletsList = new List<int[]>();
        for (int i = 0; i < array.Length - 2; i++)
        {
            int left = i+1;
            int right = array.Length -1;
            while(left < right)
            {
                int currentSum = array[i] + array[left] + array[right];
                if(targetSum == currentSum)
                {
                    int[] newTriplet = {array[i], array[left], array[right]};
                    tripletsList.Add(newTriplet);
                    left++;
                    right--;
                }
                else
                    if(currentSum > targetSum)
                    {
                        right--;
                    }
                else
                    if(currentSum < targetSum)
                    {
                        left++;
                    }
            }
        }
        return tripletsList;
    }
}

Happy to hear new approaches, Adios, Gracias...