Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
 
2.
Introduction
3.
Approach 1: Brute Force
3.1.
Algorithm
3.2.
C++ Implementation
3.3.
Java Implementation
3.4.
Python Implementation
3.5.
Complexity 
4.
Approach 2: Using Hashing
4.1.
Algorithm
4.2.
C++ Implementation
4.3.
Java Implementation
4.4.
Python Implementation
4.5.
Complexity
5.
Frequently Asked Questions
5.1.
Does аn аrrаy hаve а fixed length?
5.2.
How does а computer differentiаte а positive аnd а negаtive integer?
5.3.
Whаt is аn аrrаy аnd why it is used?
5.4.
Whаt аre the benefits of аrrаys?
5.5.
When should you use а Hаshtаble?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Find Pairs of Positive and Negative Values Present in a Given Array

Author Aditya kumar
0 upvote

 

Introduction

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.

Find pairs

Example:

Sample Input

Sample Output

Arr[]={7,3,4,-7,5,-3}

-7 7

-3 3

Arr[]={1,2,8,-1,3,-2}

-1 1

-2 2

Must Recommended Topic, Hash Function in Data Structure.

Approach 1: Brute Force

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

  1. In the range, ‘0’ to ‘n-1’, run a loop for integer ‘i’.
    1. In the range, ‘i+1’ to ‘n-1’, run a loop for integer ‘j’.
      1. If Arr[i] and -Arr[j] are equal, publish this pair.
    2. 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
Run Code

Output

Output

Java Implementation

/*
	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
Run Code

Output

Output

Python Implementation

'''
	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
Run Code

Output

Output

Complexity 

Time Complexity

Two nested loops, both of size ‘N’, are used. As a result, the overall time complexity is O(N2).

Space Complexity

SinceBecause we are not utilizing any additional space, the space complexity is O(1).

You can also read about the Longest Consecutive Sequence.

Approach 2: Using Hashing

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

  1. Initialize a hash table.
  2. Store the frequency of each element in the hash table.
  3. Run a loop for ‘i’ in range ‘0’ to ‘n-1’.
    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.
  4. 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:

Hash table

We'll now iterate through the array.

The current index is indicated by the purple color.

Step 1

Hash table

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.

Hash table

Step 2

Hash table

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.

Hash table

Step 3

Hash table

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.

Hash table

Step 4

Hash table

We are on -7, the value of 7 is 0 in the hash table, and so we will skip it.

Hash table

Step 5

Hash table

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.

Hash table

Step 6

Hash table

We are on -3, the value of 3 is 0 in the hash table, and so we will skip it.

Hash table

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
Run Code

Output

Output

Java Implementation

/*
	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
Run Code

Output

Output

Python Implementation

'''
	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
Run Code

Output

Output

Complexity

Time Complexity

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?

  1. In аn аrrаy, аccessing аn element is very eаsy by using the index number.
  2. The seаrch process cаn be аpplied to аn аrrаy eаsily.
  3. 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:


Check out the following problems - 


Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; look at the Top 150 Interview Puzzles interview experiences, and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Thank you

Happy Learning Ninja!

Live masterclass