Problem 3: Triplets | Three Number Sum | Arrays

Problem 3: Triplets | Three Number Sum | Arrays

Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. The function should and all triplets in the array that sum up to the target sum and return a two-dimensional array of all these triplets. The numbers in each triplet should be ordered in ascending order, and the triplets themselves should be ordered in ascending order with respect to the numbers they hold.

If no three numbers sum up to the target sum, the function should return an empty array.

Sample Input

array = [12, 3, 1, 2, -6, 5, -8, 6]
targetSum = 0

Sample Output

[[-8, 2, 6], [-8, 3, 5], [-6, 1, 5]]|

import java.util.*;

class Program {
  public static List<Integer[]> threeNumberSum(int[] array, int targetSum) {
    // Write your code here.
		Arrays.sort(array);
		ArrayList<Integer[]> output = new ArrayList<>();
		
		for (int cIdx = 0; cIdx < array.length - 2; cIdx++) {
			int cN = array[cIdx];
			int currentSum = 0;
			int left = cIdx + 1;
			int right = array.length - 1;
			
			while( left < right) {
				currentSum = cN + array[left] + array[right];
				if (currentSum > targetSum) {
					--right;
				}
				else if (currentSum < targetSum) {
					++left;
				}
				else {
					Integer[] match = new Integer[3];
					match[0] = cN;
					match[1] = array[left];
					match[2] = array[right];
					output.add(match);
					--right;
					++left;
				}
			}
		}
    return output;
  }
}