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:
- Sort the given array, Declare a triplets list.(List of Int Array)
- Start a loop from i = 0 till i < len(arr)- 2 [Since we use two pointers]
- Left Pointer = i+1
- Right Pointer = len(arr)-1
- Loop till Left Pointer < Right Pointer
- In every iteration find Current Sum = arr[i] + arr[left] + arr[right]
- if CurrentSum == target sum add it to the triplet list and left ++, right --
- If CurrentSum < targetSum => left++
- If CurrentSum > targetSum => right--
- 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...