Question: Can someone explain the run - time of this program for both the sorted and unsorted array. import java.util. * ; class Main { static

Can someone explain the run-time of this program for both the sorted and unsorted array.
import java.util.*;
class Main {
static class Pair {
int first;
int second;
Pair(int first, int second){
this.first = first;
this.second = second;
}
}
static Pair getCandidatePair(int[] A, int target){
HashSet set = new HashSet<>();
for (int num : A){
int complement = target - num;
if (set.contains(complement)){
return new Pair(num, complement);
}
set.add(num);
}
return new Pair(0,0);
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
scanner.nextLine(); // Consume newline
for (int i =1; i <= t; i++){
String[] statusAndSize = scanner.nextLine().split("");
int status = Integer.parseInt(statusAndSize[0]);
int size = Integer.parseInt(statusAndSize[1]);
int[] groceries = new int[size];
String[] groceriesString = scanner.nextLine().split("");
for (int j =0; j < size; j++){
groceries[j]= Integer.parseInt(groceriesString[j]);
}
int target = scanner.nextInt();
scanner.nextLine(); // Consume newline
Pair pair;
if (status ==1){
pair = getCandidatePairSorted(groceries, target);
} else {
pair = getCandidatePair(groceries, target);
}
if (pair.first !=0 && pair.second !=0){
System.out.println("Test case #"+ i +": Spend "+ target +" dollars by buying the groceries with "+ Math.min(pair.first, pair.second)+" dollars and "+ Math.max(pair.first, pair.second)+" dollars.");
} else {
System.out.println("Test case #"+ i +": No way you can spend exactly "+ target +" dollars.");
}
}
}
static Pair getCandidatePairSorted(int[] A, int target){
int left =0, right = A.length -1;
while (left < right){
int sum = A[left]+ A[right];
if (sum == target){
return new Pair(A[left], A[right]);
} else if (sum < target){
left++;
} else {

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!