Target Sun Pair [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 pairs of numbers which sum to target.


Input Format
The first line contains input N. Next N lines contains the elements of array and (N+1)th line contains target number.

Constraints
Length of the arrays should be between 1 and 1000.

Output Format
Print all the pairs of numbers which sum to target. Print each pair in increasing order.

Sample Input
5
1
3
4
2
5
5

Sample Output
1 and 4
2 and 3

Explanation
Find any pair of elements in the array which has sum equal to target element and print them.


Java Code:



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

package array;
import java.util.Scanner;

public class Array_TargetSumPair {
    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) {
        int head, tail;
        head = 0;
        tail = arr.length-1;

        while (head < tail) {
            if (arr[head] + arr[tail] == targetSum) {
                System.out.println(arr[head] + " and " + arr[tail]);
                head++;
                tail--;
            } else if (arr[head] + arr[tail] > 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 )