Question

In: Computer Science

Let's say someone gives you an array that is filled with P numbers. Please next see...

Let's say someone gives you an array that is filled with P numbers. Please next see if there are two numbers whose sum equals a given number S and determine if there is two numbers that do this. Take for example, if I give you the input array to be 8, 2, 1, 7, and our variable S is 15, then the answer would be yes because 8 and 7 add up to S which in this case is 15. You are allowed to use a number twice. To solve this problem, please  Give me an O(NlogN) algorithm. (In language C++)

Solutions

Expert Solution

Code:

#include<iostream>
using namespace std;
bool check_pair(int *arr,int n,int sum){
         int first=0,last=n-1;
   while(first<last){
        if (arr[first]+arr[last]<sum)
                first++;
        else if (arr[first]+arr[last]>sum)
        last--;
        else return 1;
   }
}
void swapping(int &a, int &b) {     //swap the content of a and b
   int temp;
   temp = a;
   a = b;
   b = temp;
}
void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}
void merge(int *array, int l, int m, int r) {
   int i, j, k, nl, nr;
   //size of left and right sub-arrays
   nl = m-l+1; nr = r-m;
   int larr[nl], rarr[nr];
   //fill left and right sub-arrays
   for(i = 0; i<nl; i++)
      larr[i] = array[l+i];
   for(j = 0; j<nr; j++)
      rarr[j] = array[m+1+j];
   i = 0; j = 0; k = l;
   //marge temp arrays to real array
   while(i < nl && j<nr) {
      if(larr[i] <= rarr[j]) {
         array[k] = larr[i];
         i++;
      }else{
         array[k] = rarr[j];
         j++;
      }
      k++;
   }
   while(i<nl) {       //extra element in left array
      array[k] = larr[i];
      i++; k++;
   }
   while(j<nr) {     //extra element in right array
      array[k] = rarr[j];
      j++; k++;
   }
}
void mergeSort(int *array, int l, int r) {
   int m;
   if(l < r) {
      int m = l+(r-l)/2;
      // Sort first and second arrays
      mergeSort(array, l, m);
      mergeSort(array, m+1, r);
      merge(array, l, m, r);
   }
}
int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n];     //create an array with given number of elements
   cout << "Enter elements:" << endl;
   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }
   cout << "Array before Sorting: ";
   display(arr, n);
   mergeSort(arr, 0, n-1);     //(n-1) for last index
   cout << "Array after Sorting: ";
   display(arr, n);
   //solution for your question starts here.
   printf("enter the sum for which you want to find pair\n");
   int sum;
   scanf("%d",&sum);
   bool con=check_pair(arr,n,sum);
   if (con)
        cout<<"pair available\n";
   else
        cout<<"pair unavailable\n";
   return 0;

}

Explanation:

Algorithm:

1.sort array (merge sort o(n log n)

2. Take two pointers first and last.

3. while(first<last)

do{

if arr[first]+arr[last]<sum

first++

else if arr[first]+arr[last]>sum

last--

else

return 1

}--->o(n)

This whole program takes total complexity o(nlogn)

Hope it helps.

I hope you will accept my answer


Related Solutions

You are given an array of length n that is filled with two symbols (say 0...
You are given an array of length n that is filled with two symbols (say 0 and 1); all m copies of one symbol appear first, at the beginning of the array, followed by all n − m copies of the other symbol. You are to find the index of the first copy of the second symbol in time O(logm). include: code,  proof of correctness, and runtime analysis  
Let's say you want to poll a random sample of 150 students on campus to see...
Let's say you want to poll a random sample of 150 students on campus to see if they prefer to take online classes. Of course, if you took an actual poll you would only get one number (your sample proportion, p-hat). But, imagine all the possible samples of 150 students that you could draw and the imagined histogram of all the sample proportions from those samples. 1. What shape would the histogram of all the possible sample proportions (p-hat's) have?...
Given an array A of n distinct real numbers, we say that a pair of numbers...
Given an array A of n distinct real numbers, we say that a pair of numbers i, j ∈ {0, . . . , n−1} form an inversion of A if i < j and A[i] > A[j]. Let inv(A) = {(i, j) | i < j and A[i] > A[j]}. Answer the following: (a) How small can the number of inversions be? Give an example of an array of length n with the smallest possible number of inversions. (b)...
Given an array A of n distinct numbers, we say that a pair of numbers i,...
Given an array A of n distinct numbers, we say that a pair of numbers i, j ∈ {0, . . . , n − 1} form an inversion of A if i < j and A[i] > A[j]. Let inv(A) = {(i, j) | i < j and A[i] > A[j]}. Define the Inversion problem as follows: • Input: an array A consisting of distinct numbers. • Output: the number of inversions of A, i.e. |inv(A)|. Answer the following:...
Suppose someone gives you 1414 to 44 odds that you cannot roll two even numbers with...
Suppose someone gives you 1414 to 44 odds that you cannot roll two even numbers with the roll of two fair dice. This means you win ​$1414 if you succeed and you lose ​$44 if you fail. What is the expected value of this game to​ you? Should you expect to win or lose the expected value in the first​ game? What can you expect if you play 200200 ​times? Explain.​ (The table will be helpful in finding the required​ probabilities.) LOADING... Click the...
Let's say that you are an athletic trainer, and you are interested in the impact of...
Let's say that you are an athletic trainer, and you are interested in the impact of different types of exercise upon resting heart beats. You run a study comparing people who do yoga, pilates, and runners. You have collected the data and you are ready to analyze it via ANOVA. Using JASP, conduct your ANOVA. Then complete the fill-in-the-blank sentence below. HBM Sport 59 Yoga 60 Yoga 60 Yoga 55 Yoga 61 Yoga 59 Yoga 58 Yoga 60 Yoga 60...
Let's look at Tesla's profitability. What do the numbers say? Is Tesla profitable? Does it have...
Let's look at Tesla's profitability. What do the numbers say? Is Tesla profitable? Does it have a competitive advantage? Motivate your responses.
IN JAVA PLEASE Given an unsorted array numbers of integers with duplicate values. Sort the array...
IN JAVA PLEASE Given an unsorted array numbers of integers with duplicate values. Sort the array and remove the duplicates in-place such that each element appears only once in the input array and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Find the time complexity of your removeDuplicates() method in Big-O notation and write that in a comment line on the top...
Please, write a loop to print odd numbers an array a with pointers backwards. You can...
Please, write a loop to print odd numbers an array a with pointers backwards. You can use a variable “size” for array size.
Please state the step number next to the answers, thank you! The following table gives the...
Please state the step number next to the answers, thank you! The following table gives the average number of hours 7 junior high students were left unsupervised each day and their corresponding overall grade averages. Hours Unsupervised 0 0.5 1.5 2.5 3.5 4.5 5 Overall Grades 96 88 84 80 76 72 68 Step 1 of 3: Calculate the correlation coefficient, r. Round your answer to six decimal places. Step 2 of 3: Determine if r is statistically significant at...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT