In the problem statement to find pairs of positive and negative values present in a given array, given an array A of distinct integers, which will output all the pairs in the array that contain a positive and negative value. We must print pairings in the order in which they occur. Any element that appears first in a pair should be printed first.
Check if -Arr[i](negative values) is present in the array with an index larger than i for each element Arr[i](positive values) in the input array, and if so, output this pair.
Algorithm
In the range, ‘0’ to ‘n-1’, run a loop for integer ‘i’.
In the range, ‘i+1’ to ‘n-1’, run a loop for integer ‘j’.
If Arr[i] and -Arr[j] are equal, publish this pair.
Return.
C++ Implementation
/*
C++ Program to implement the problem to find pairs of positive and negative values present in a given array.
*/
#include <bits/stdc++.h>
using namespace std;
void printPosNegPairs(vector<int> &Arr)
{
int n = Arr.size();
cout<<"The positive and negative pairs are:"<<endl;
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (Arr[i] == -Arr[j])
{
if (Arr[i] <= 0)
{
cout << Arr[i] << " " << (-Arr[i]) << " "<<endl;
}
else
{
cout << (-Arr[i]) << " " << Arr[i] << " "<<endl;
}
}
}
}
cout << endl;
return;
}
int main()
{
vector<int> Arr;
cout<<"Enter the Array Size: ";
int n;
cin>>n;
cout<<"Enter the Elements in the Array"<<endl;
for(int i=0;i<n;i++)
{
int a;
cin>>a;
Arr.push_back(a);
}
printPosNegPairs(Arr);
return 0;
}
You can also try this code with Online C++ Compiler
/*
Java Program to implement the problem to find pairs of positive and negative values present in a given array.
*/
import java.util.*;
public class Main
{
static void printPosNegPairs(int[] Arr)
{
int n = Arr.length;
System.out.println("The positive and negative pairs are:");
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (Arr[i] == -Arr[j])
{
if (Arr[i] <= 0)
{
Arr[i]=-Arr[i];
}
System.out.println(-Arr[i]+" "+Arr[i]+" ");
}
}
}
return;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter the Array Size: ");
int n=sc.nextInt();
int Arr[]=new int[n];
System.out.println("Enter the Elements in the Array");
for(int i=0;i<n;i++)
{
Arr[i]=sc.nextInt();}
printPosNegPairs(Arr);
}
}
You can also try this code with Online Java Compiler
'''
Python program to implement the problem to find pairs of positive and negative values present in a given array.
'''
def printPosNegPairs(Arr, n):
newArr = []
print("The positive and negative pairs are:")
for i in range(n):
for j in range(i + 1, n):
if (abs(Arr[i]) == abs(Arr[j])):
newArr.append(abs(Arr[i]))
if (len(newArr) == 0):
return
for i in range(len(newArr)):
print(-newArr[i], "", newArr[i], end=" ")
print()
if __name__ == "__main__":
Arr = []
n = int(input("Enter the Array Size: "))
print("Enter the Elements in the Array")
for i in range(0, n):
ele = int(input())
Arr.append(ele)
printPosNegPairs(Arr, n)
You can also try this code with Online Python Compiler
In a hash table, we can keep track of which elements are in the array. Check if -Arr[i] in the hash table has a value of 1 for each element Arr[i] in the array; if it does, print this pair and decrease the value of Arr[i] and –Arr[i] in the hash table by 1 so that we don't display the same pair twice.
Algorithm
Initialize a hash table.
Store the frequency of each element in the hash table.
Run a loop for ‘i’ in range ‘0’ to ‘n-1’.
If -Arr[i] has a value of 1 in the hash table, then print this pair and decrement the value of Arr[i] and -Arr[i] by 1.
Return.
Let us take an example to understand the working of this algorithm.
For example, the input array is Arr[]={7,3,4,-7,5,-3}
So for this example our hash table will look like this:
We'll now iterate through the array.
The current index is indicated by the purple color.
Step 1
We are on 7, a value of -7 is 1 in the hash table, so we will print this pair and will decrement the value of 7 and -7 by 1.
Step 2
We are on 3, the value of -3 is 1 in the hash table, so we will print this pair decrement the value by 1.
Step 3
We are on 4, the value of -4 is 0 in the hash table because it is not present in the hash table, so we will take it as zero, and so we will skip it.
Step 4
We are on -7, the value of 7 is 0 in the hash table, and so we will skip it.
Step 5
We are on 5, the value of -5 is 0 in the hash table because it is not present in the hash table, so we will take it as zero, and so we will skip it.
Step 6
We are on -3, the value of 3 is 0 in the hash table, and so we will skip it.
So the final output is: -7 7 -3 3
C++ Implementation
/*
C++ program to implement the problem to find pairs of positive and negative values present in a given array.
*/
#include <bits/stdc++.h>
using namespace std;
void printPosNegPairs(vector<int> &Arr)
{
int n = Arr.size();
unordered_map<int, int> hash_table;
cout<<"The positive and negative pairs are:"<<endl;
for (int i = 0; i < n; i++)
{
hash_table[Arr[i]]++;
}
for (int i = 0; i < n; i++)
{
if (hash_table[-Arr[i]] == 1)
{
if (Arr[i] <= 0)
{
cout << Arr[i] << " " << (-Arr[i]) << " "<<endl;
}
else
{
cout << (-Arr[i]) << " " << Arr[i] << " "<<endl;
}
hash_table[Arr[i]]--;
hash_table[-Arr[i]]--;
}
}
cout << endl;
return;
}
int main()
{
vector<int> Arr;
cout<<"Enter the Array Size: ";
int n;
cin>>n;
cout<<"Enter the Elements in the Array"<<endl;
for(int i=0;i<n;i++)
{
int a;
cin>>a;
Arr.push_back(a);
}
printPosNegPairs(Arr);
return 0;
}
You can also try this code with Online C++ Compiler
/*
Java program to implement the problem to find pairs of positive and negative values present in a given array.
*/
import java.util.*;
public class Main
{
static void printPosNegPairs(int[] Arr)
{
int n = Arr.length;
System.out.println("The positive and negative pairs are:");
HashMap<Integer,Integer> hash_table = new HashMap<Integer,Integer>();
for (int i = 0; i < n; i++)
{
hash_table.put(Arr[i],1);
}
for (int i = 0; i < n; i++)
{
if(hash_table.containsKey(-1*Arr[i]) && hash_table.get(-1*Arr[i])==1)
{
if (Arr[i] <= 0)
{
Arr[i]*=-1;
}
System.out.println(-Arr[i]+" "+Arr[i]+" ");
hash_table.put(Arr[i],0);
hash_table.put(-1*Arr[i],0);
}
}
return;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter the Array Size: ");
int n=sc.nextInt();
int Arr[]=new int[n];
System.out.println("Enter the Elements in the Array");
for(int i=0;i<n;i++)
{
Arr[i]=sc.nextInt();}
printPosNegPairs(Arr);
}
}
You can also try this code with Online Java Compiler
'''
Python program to implement the problem to find pairs of positive and negative values present in a given array.
'''
def printPosNegPairs(Arr, n):
s = set()
newArr = []
print("The positive and negative pairs are:")
for i in Arr:
if abs(i) in s:
newArr.append(abs(i))
else:
s.add(abs(i))
newArr.sort()
for i in range(0, len(newArr)):
print(-newArr[i], "", newArr[i], end=" ")
print()
if __name__ == "__main__":
Arr = []
n = int(input("Enter the Array Size: "))
print("Enter the Elements in the Array")
for i in range(0, n):
ele = int(input())
Arr.append(ele)
printPosNegPairs(Arr, n)
You can also try this code with Online Python Compiler
Since we are iterating through the entire array twice, the time complexity is O(2N) so we can consider as O(N).
Space Complexity
Since we're working with a hash table, the space complexity is O(N).
Frequently Asked Questions
Does аn аrrаy hаve а fixed length?
Yes, An аrrаy is а contаiner object thаt holds а fixed number of vаlues of а single type.
How does а computer differentiаte а positive аnd а negаtive integer?
Computers use the first bit to indicate this. If the first bit is 1, the number is negаtive. If the first bit is 0, the number is positive.
Whаt is аn аrrаy аnd why it is used?
An аrrаy is а collection of items, or dаtа, stored in contiguous memory locations. The purpose of аn аrrаy is to store multiple pieces of dаtа of the sаme type-together.
Whаt аre the benefits of аrrаys?
In аn аrrаy, аccessing аn element is very eаsy by using the index number.
The seаrch process cаn be аpplied to аn аrrаy eаsily.
2D Arrаy is used to represent mаtrices.
When should you use а Hаshtаble?
We cаn use hаsh tаbles to store, retrieve, аnd delete dаtа uniquely bаsed on their unique key.
Conclusion
In this аrticle, we hаve used the hаshing technique to аddress the problem to find pairs of positive and negative values present in a given array. We аlso leаrned the C++, Jаvа, and Python progrаm for this problem, аs well аs the entire аpproаch (brute force аnd efficient аpproаch) thаt we used to solve it.
We hope this blog has helped you enhance your knowledge regarding the problem to find pairs of positive and negative values present in a given array. If you want to learn more about interview questions, visit the links below: