Print all the pairs that contains the positive and negative values of an element in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of unique integers. And we have to return all pairs of integers(positive and negative integers) that are present in the array.

Let’s take an example to understand the problem better −

Input: array = {1 , 4 , 7 , -1, 2, 5, -7}
Output: -11 -33

An easy way to solve the problem is by using two loops and find the positive-negative pairs. But this solution will be a complex one and will have time complexity of the order n2 where n is the size of the array.

But, we have to find a more efficient approach to solve the problem. For that, we will first sort the array. And then in this sorted array, for every negative integer find the opposite (positive) integer. This binary search will be a good approach. And print the pairs that are found using the search.

Example

Let’s see a code illustration of this method −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void positiveNegativePair(int arr[], int n) ;
int main(){
   int arr[] = { 1, 4, 6 , 3, -1, -2, 5, -6, -5 , 8 };
   int n = 10;
   cout<<"Postive Negative pairs in the array are :\n";
   positiveNegativePair(arr, n);
   return 0;
}
void positiveNegativePair(int arr[], int n){
   bool pair_exists = false;
   sort(arr, arr + n);
   for (int i = 0; i < n; i++) {
      if (arr[i] < 0) {
         if (binary_search(arr, arr + n, -arr[i])) {
            cout<<arr[i]<<", "<<-arr[i]<<"\t";
            pair_exists = true;
         }
      }
      else
         break;
   }
   if (!pair_exists)
      cout << "No positive-negative pairs exist in the code";
}

Output

Positive Negative pairs in the array are −

-6, 6 -5, 5 -1, 1
raja
Published on 17-Jan-2020 09:58:19
Advertisements