Target Sum Triplet [codingblocks]

Take as input N, the size of array. Take N more inputs and store that in an array. Take as input “target”, a number. Write a function which prints all triplets of numbers which sum to target.


Input Format
First line contains input N.
Next line contains N space separated integers denoting the elements of the array.
The third line contains a single integer T denoting the target element.

Constraints
Length of Array should be between 1 and 1000.

Output Format
Print all the triplet present in the array in a new line each. The triplets must be printed as A, B and C where A,B and C are the elements of the triplet ( A<=B<=C) and all triplets must be printed in sorted order. Print only unique triplets.

Sample Input
9
5 7 9 1 2 4 6 8 3
10

Sample Output
1, 2 and 7
1, 3 and 6
1, 4 and 5
2, 3 and 5

Explanation
Array = {5, 7, 9, 1, 2, 4, 6 ,8 ,3}. Target number = 10. Find any three number in the given array which sum to target number.


Java Code:



/*
Amit Kumar
04-12-2020
IDE Code: https://ide.geeksforgeeks.org/2rhRQvvxI8
*/

package array;
import java.util.Scanner;

public class Array_TargetSumTriplet {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String [] args) {
        int arrSize = scanner.nextInt();
        int [] arr = new int[arrSize];
        for (int i=0; i<arrSize; i++) {
            arr[i] = scanner.nextInt();
        }
        int targetSum = scanner.nextInt();
        bubbleSort(arr);
        printTargetSum(arr, targetSum);
    }

    public static void printTargetSum(int[] arr, int targetSum) {
        for (int i=0 ; i<arr.length-2 ; i++) {
            int head, tail;
            head = i+1;
            tail = arr.length-1;

            while (head < tail) {
                if (arr[head] + arr[tail] + arr[i] == targetSum) {
                    System.out.println(arr[i] + ", " + arr[head] + " and " + arr[tail]);
                    head++;
                    tail--;
                } else if (arr[head] + arr[tail] + arr[i] > targetSum) {
                    tail--;
                } else {
                    head++;
                }
            }
        }
    }

    public static void bubbleSort(int[] arr) {
        for (int i=0; i<arr.length; i++) {
            for (int j=0; j<arr.length-i-1; j++) {
                if (arr[j] > arr[j+1]) {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    }
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )