Monday, 14 August 2017

Write a program in JAVA where the sum of two elements of an array indices a specific target.

Another tricky question for java job seekers. You are given an array and a target element. You have to find out the sum of two elements which is equal to the specific target.

We will solve this approach by using Map. Time complexity would be O(n).

Sample Input:

Given array ={2,7,11,15};
Target element= 9
Output would be : 2 & 7.


Code:

public class SumOfTwoTarget {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
        int nums[]={2,7,11,15};
        Scanner in=new Scanner(System.in);
        System.out.println("Please enter the target: \n");
        int target=in.nextInt();
        checkTargetExist(nums,target);

    }
// Logic is substract each element of that array from target and assign it to a variable called element.
//If that element is present in the map, then return that key else add the array element in map and continue. 


    private static void checkTargetExist(int[] nums, int target) {
        Map<Integer, Integer> map=new HashMap<>();
        for(int i=0;i<nums.length;i++)
        {
            int element=target-nums[i];
            if(map.containsKey(element))
            {
                System.out.println("Target is present: values are: "+ map.get(element)+ " = "+i);
                return;
            }
            map.put(nums[i],i);
        }
        System.out.println("Sorry: Target is not present");
    }
}



Sample Output:

Please enter the target:
9
Target is present: values are: 0 = 1
 

1 comment:

  1. Hi,
    I don't use map in this programing.
    Just use basic loop.

    Please check the below.

    package com;

    import java.util.Scanner;

    public class SumOfTwoTarget {
    static int element;
    public static void findNo(int nums[],int target ) {
    try {
    for (int i = 0; i < nums.length; i++) {
    for (int j = i+1; j < nums.length; j++) {
    if (target==nums[i]+nums[j]) {
    System.out.println(i+ " & " +j);
    }
    else {
    System.out.println("Not found");
    }
    }
    }
    } catch (Exception e) {
    e.printStackTrace();// TODO: handle exception
    }

    }


    public static void main(String[] args) {
    // TODO Auto-generated method stub
    int nums[]={2,7,11,15};
    Scanner in=new Scanner(System.in);
    System.out.println("Please enter the target: \n");
    int target=in.nextInt();
    findNo(nums,target);
    }

    }

    ReplyDelete

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...