Java program to check if two elements of an array adds to the given sum
Hi everyone, in this blog post, I will be discussing about a famous java program, which is to check if two elements of an array adds to the given sum. Problem Given an array with elements and a sum. Check whether any 2 elements of the array adds to the given sum. Return true if the sum is present, else return false. Example Given an array {1,2,4}. The array should return true for the sum 5 and false for 4. Solution The basic solution which comes to everyone's mind would be to check each element with each other elements for the given sum. But the total time complexity in doing that will be O(n^2). We will approach the problem in a much easier way. The logic for that is as follows: Sort the given array in ascending order. Create two variables, one which tracks from the first position of array ( pos_first ) and other which tracks from the last position of the array ( pos_last ). While pos_first is less than pos_last , do the below steps. Add the elements corr...