Print all the pairs that contains the positive and negative values of an element
Last Updated :
30 Oct, 2023
Given an array of distinct integers, print all the pairs having a positive value and negative value of a number that exists in the array.
Note: Order of the pairs doesn’t matter.
Examples:
Input: arr[] = { 1, -3, 2, 3, 6, -1 }
Output: -1 1 -3 3
Input: arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }
Output: -1 1 -4 4 -8 8 -9 9
Naive approach(using two loops)
Algorithm
Initialize an array with 6 integers.
Find the size of the array.
Loop through each element in the array.
For each element, loop through each element after it.
For each pair of elements, check if they have opposite signs and equal absolute values.
If the condition is true, print the two elements.
Repeat steps 4-6 for all pairs of elements.
End the program.
Implementation of following approach
C++
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int arr[] = { 1, -3, 2, 3, 6, -1 };
int n = sizeof (arr) / sizeof (arr[0]);
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
if ((arr[i] > 0 && arr[j] < 0 && abs (arr[i]) == abs (arr[j])) ||
(arr[i] < 0 && arr[j] > 0 && abs (arr[i]) == abs (arr[j]))) {
if (arr[i] < 0) {
cout << arr[i] << " " << arr[j] << endl;
} else {
cout << arr[j] << " " << arr[i] << endl;
}
}
}
}
return 0;
}
|
Java
import java.util.Arrays;
public class GFG {
public static void main(String[] args) {
int [] arr = { 1 , - 3 , 2 , 3 , 6 , - 1 };
int n = arr.length;
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
if ((arr[i] > 0 && arr[j] < 0 && Math.abs(arr[i]) == Math.abs(arr[j])) ||
(arr[i] < 0 && arr[j] > 0 && Math.abs(arr[i]) == Math.abs(arr[j]))) {
if (arr[i] < 0 ) {
System.out.println(arr[i] + " " + arr[j]);
} else {
System.out.println(arr[j] + " " + arr[i]);
}
}
}
}
}
}
|
Python
arr = [ 1 , - 3 , 2 , 3 , 6 , - 1 ]
n = len (arr)
for i in range (n):
for j in range (i + 1 , n):
if ((arr[i] > 0 and arr[j] < 0 and abs (arr[i]) = = abs (arr[j])) or
(arr[i] < 0 and arr[j] > 0 and abs (arr[i]) = = abs (arr[j]))):
if arr[i] < 0 :
print (arr[i], arr[j])
else :
print (arr[j], arr[i])
|
C#
using System;
class Program
{
static void Main( string [] args)
{
int [] arr = { 1, -3, 2, 3, 6, -1 };
int n = arr.Length;
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
{
if ((arr[i] > 0 && arr[j] < 0 && Math.Abs(arr[i]) == Math.Abs(arr[j])) ||
(arr[i] < 0 && arr[j] > 0 && Math.Abs(arr[i]) == Math.Abs(arr[j])))
{
if (arr[i] < 0)
{
Console.WriteLine(arr[i] + " " + arr[j]);
}
else
{
Console.WriteLine(arr[j] + " " + arr[i]);
}
}
}
}
}
}
|
Javascript
const arr = [1, -3, 2, 3, 6, -1];
const n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if ((arr[i] > 0 && arr[j] < 0 && Math.abs(arr[i]) === Math.abs(arr[j])) ||
(arr[i] < 0 && arr[j] > 0 && Math.abs(arr[i]) === Math.abs(arr[j]))) {
if (arr[i] < 0) {
console.log(arr[i], arr[j]);
} else {
console.log(arr[j], arr[i]);
}
}
}
}
|
Time complexity O(n^2), where n is the size of the input array.
Auxiliary Space O(1), as it uses a constant amount of additional memory to store variables like the loop counters and the array elements.
A better approach is to use sorting i.e. first sort the array and then for each negative element, do a binary search to find its counterpart (+ve number). If found, print that pair. If the current element is positive then break that loop as after that there will be all the positive numbers.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void printPairs( 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] << endl;
pair_exists = true ;
}
}
else
break ;
}
if (pair_exists == false )
cout << "No such pair exists" ;
}
int main()
{
int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
int n = sizeof (arr) / sizeof (arr[0]);
printPairs(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void printPairs( int arr[], int n)
{
boolean pair_exists = false ;
Arrays.sort(arr);
for ( int i = 0 ; i < n; i++)
{
if (arr[i] < 0 )
{
if (java.util.Arrays.binarySearch(arr, -arr[i])!=- 1 )
{
System.out.println(arr[i] + ", " + -arr[i] );
pair_exists = true ;
}
}
else
break ;
}
if (pair_exists == false )
System.out.println( "No such pair exists" );
}
public static void main(String args[])
{
int arr[] = { 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 };
int n =arr.length;
printPairs(arr, n);
}
}
|
Python 3
def binary_search(a, x, lo = 0 , hi = None ):
if hi is None :
hi = len (a)
while lo < hi:
mid = (lo + hi) / / 2
midval = a[mid]
if midval < x:
lo = mid + 1
elif midval > x:
hi = mid
else :
return mid
return - 1
def printPairs(arr, n):
pair_exists = False
arr.sort()
for i in range (n):
if (arr[i] < 0 ):
if (binary_search(arr, - arr[i])):
print (arr[i] , ", " , - arr[i])
pair_exists = True
else :
break
if (pair_exists = = False ):
print ( "No such pair exists" )
if __name__ = = '__main__' :
arr = [ 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 ]
n = len (arr)
printPairs(arr, n)
|
C#
using System;
public class GFG{
static void printPairs( int []arr, int n)
{
bool pair_exists = false ;
Array.Sort(arr);
for ( int i = 0; i < n; i++)
{
if (arr[i] < 0)
{
if (Array.BinarySearch(arr, -arr[i])!=-1)
{
Console.WriteLine(arr[i] + ", " + -arr[i] );
pair_exists = true ;
}
}
else
break ;
}
if (pair_exists == false )
Console.WriteLine( "No such pair exists" );
}
public static void Main()
{
int []arr = { 4, 8, 9, -4, 1, -1, -8, -9 };
int n =arr.Length;
printPairs(arr, n);
}
}
|
Javascript
function printPairs(arr, n) {
let pair_exists = false ;
arr.sort((a, b) => a - b);
for (let i = 0; i < n; i++) {
if (arr[i] < 0) {
if (arr.includes(-arr[i])) {
document.write(arr[i] + ", " + -arr[i] + "<br>" );
pair_exists = true ;
}
}
else
break ;
}
if (pair_exists == false )
document.write( "No such pair exists" );
}
let arr = [4, 8, 9, -4, 1, -1, -8, -9];
let n = arr.length;
printPairs(arr, n);
|
Output
-9, 9
-8, 8
-4, 4
-1, 1
Time Complexity: O(n log n)
Auxiliary Space: O(1)
An efficient approach is to use hashing. Below are the required steps:
- Start traversing the array.
- Store all the positive values in an unordered_set.
- Check for each negative element, if their corresponding positive element exists in the set or not.
- If yes, print the pair
- Also, maintain a flag to check if no such pair exists.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void printPairs( int arr[], int n)
{
unordered_set< int > pairs;
bool pair_exists = false ;
for ( int i = 0; i < n; i++)
if (arr[i] > 0)
pairs.insert(arr[i]);
for ( int i = 0; i < n; i++) {
if (arr[i] < 0)
if (pairs.find(-arr[i]) != pairs.end())
{
cout << arr[i] << ", " << -arr[i] << endl;
pair_exists = true ;
}
}
if (pair_exists == false )
cout << "No such pair exists" ;
}
int main()
{
int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
int n = sizeof (arr) / sizeof (arr[0]);
printPairs(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void printPairs( int arr[], int n)
{
Set<Integer> pairs = new HashSet<Integer>();
boolean pair_exists = false ;
for ( int i = 0 ; i < n; i++)
if (arr[i] > 0 )
pairs.add(arr[i]);
for ( int i = 0 ; i < n; i++)
{
if (arr[i] < 0 )
if (pairs.contains(-arr[i]))
{
System.out.println(arr[i] + ", " + -arr[i]);
pair_exists = true ;
}
}
if (pair_exists == false )
System.out.println( "No such pair exists" );
}
public static void main(String args[])
{
int arr[] = { 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 };
int n = arr.length;
printPairs(arr, n);
}
}
|
Python3
def printPairs(arr, n):
pairs = set ()
pair_exists = False
for i in range ( 0 , n):
if arr[i] > 0 :
pairs.add(arr[i])
for i in range ( 0 , n):
if arr[i] < 0 :
if ( - arr[i]) in pairs:
print ( "{}, {}" . format (arr[i], - arr[i]))
pair_exists = True
if pair_exists = = False :
print ( "No such pair exists" )
if __name__ = = "__main__" :
arr = [ 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 ]
n = len (arr)
printPairs(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void printPairs( int []arr, int n)
{
HashSet< int > pairs = new HashSet< int >();
bool pair_exists = false ;
for ( int i = 0; i < n; i++)
if (arr[i] > 0)
pairs.Add(arr[i]);
for ( int i = 0; i < n; i++)
{
if (arr[i] < 0)
if (pairs.Contains(-arr[i]))
{
Console.WriteLine(arr[i] + ", " + -arr[i]);
pair_exists = true ;
}
}
if (pair_exists == false )
Console.WriteLine( "No such pair exists" );
}
public static void Main(String []args)
{
int []arr = { 4, 8, 9, -4, 1, -1, -8, -9 };
int n = arr.Length;
printPairs(arr, n);
}
}
|
Javascript
<script>
function printPairs(arr,n)
{
let pairs = new Set();
let pair_exists = false ;
for (let i = 0; i < n; i++)
if (arr[i] > 0)
pairs.add(arr[i]);
for (let i = 0; i < n; i++)
{
if (arr[i] < 0)
if (pairs.has(-arr[i]))
{
document.write(arr[i] + ", " + -arr[i]+ "<br>" );
pair_exists = true ;
}
}
if (pair_exists == false )
document.write( "No such pair exists" );
}
let arr=[4, 8, 9, -4, 1, -1, -8, -9];
let n = arr.length;
printPairs(arr, n);
</script>
|
Output
-4, 4
-1, 1
-8, 8
-9, 9
Time Complexity: O(n)
Auxiliary Space: O(n) because using unordered_set
Share your thoughts in the comments
Please Login to comment...