In: Computer Science
Consider the following checkSum() method where N numbers are
saved in an array (as sorted in as-
cending order). In the main() function, the user will input a
number. The checkSum() method will
find out whether the sum of any two numbers in the array is
equal to the given number by the user. You
need to solve the problem with minimum time complexity (low
complexity will lead to higher marks!).
Here Iam providing the code and the output for the problem
Time Complexity of the code : We traverse the array only one time so the time complexity is O(n).Its the best time complexity we can have.
Code for Main.java
Sample Output 1
Sample Output 2
Code for Main.java
import java.util.Scanner;
public class Main
{
static void checkSum(int sum){
int[] arr = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
int left = 0,right = 9;
while(left < right){
if(sum > arr[left] + arr[right]) //if sum is greater than sum
pair we increment left pointer
left++;
if(sum < arr[left] + arr[right]) //if sum is less than sum pair
we increment right pointer
right--;
if(sum == arr[left] + arr[right]){
System.out.print("("+arr[left]+","+arr[right]+") "); //we print if
pair equals to sum
left++;
right--;
}
}
}
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
System.out.print("Enter the sum :
");
int sum = sc.nextInt();
checkSum(sum);
}
}
NOTE : If you got the output correct please give me a THUMBS UP. Let me know in the comments if you have any doubts.Thank you