Open In App

Find pairs of Positive and Negative values present in given array

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of distinct integers, print all the pairs having both positive and negative values of a number that exists in the array. The pairs can be printed in any order.

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: -4 4 -8 8 -9 9 -1 1

Recommended Practice

Naive Approach: To solve the problem follow the below idea:

The idea is to use two nested loops. For each element arr[i], find negative of arr[i] from index i + 1 to n – 1 and store it in another array

Below is the implementation of this approach:

C++




// Simple CPP program to find pairs of positive
// and negative values present in an array.
#include <bits/stdc++.h>
using namespace std;
 
// Print pair with negative and positive value
void printPairs(int arr[], int n)
{
    vector<int> v;
 
    // For each element of array.
    for (int i = 0; i < n; i++)
 
        // Try to find the negative value of
        // arr[i] from i + 1 to n
        for (int j = i + 1; j < n; j++)
 
            // If absolute values are equal print pair.
            if (abs(arr[i]) == abs(arr[j]))
                v.push_back(abs(arr[i]));
 
    // If size of vector is 0, therefore there is no
    // element with positive negative value, print "0"
    if (v.size() == 0)
        return;
 
    // Print the pair with negative positive value.
    for (int i = 0; i < v.size(); i++)
        cout << -v[i] << " " << v[i] << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printPairs(arr, n);
    return 0;
}


Java




// Java program to find pairs of positive
// and negative values present in an array.
import java.lang.*;
import java.util.*;
 
class GFG {
 
    // Print pair with negative and positive value
    public static void printPairs(int arr[], int n)
    {
        Vector<Integer> v = new Vector<Integer>();
        // For each element of array.
        for (int i = 0; i < n; i++)
 
            // Try to find the negative value of
            // arr[i] from i + 1 to n
            for (int j = i + 1; j < n; j++)
 
                // If absolute values are equal
                // print pair.
                if (Math.abs(arr[i]) == Math.abs(arr[j]))
                    v.add(Math.abs(arr[i]));
 
        // If size of vector is 0, therefore there
        // is no element with positive negative
        // value, print "0"
        if (v.size() == 0)
            return;
 
        // Print the pair with negative positive
        // value.
        for (int i = 0; i < v.size(); i++)
            System.out.print(-v.get(i) + " " + v.get(i)
                             + " ");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
        int n = arr.length;
 
        // Function call
        printPairs(arr, n);
    }
}
 
// This code is contributed by Prasad Kshirsagar.


Python 3




# Simple Python 3 program to find
# pairs of positive and negative
# values present in an array.
 
# Print pair with negative and
# positive value
 
 
def printPairs(arr, n):
    v = []
 
    # For each element of array.
    for i in range(n):
 
        # Try to find the negative value
        # of arr[i] from i + 1 to n
        for j in range(i + 1, n):
 
            # If absolute values are
            # equal print pair.
            if (abs(arr[i]) == abs(arr[j])):
                v.append(abs(arr[i]))
 
    # If size of vector is 0, therefore
    # there is no element with positive
    # negative value, print "0"
    if (len(v) == 0):
        return
 
    # Print the pair with negative
    # positive value.
    for i in range(len(v)):
        print(-v[i], "", v[i], end=" ")
 
 
# Driver Code
if __name__ == "__main__":
    arr = [4, 8, 9, -4, 1, -1, -8, -9]
    n = len(arr)
 
    # Function call
    printPairs(arr, n)
 
# This code is contributed
# by ChitraNayal


C#




// C# program to find pairs of positive
// and negative values present in an array.
using System;
using System.Collections.Generic;
 
class GFG {
 
    // Print pair with negative and positive value
    public static void printPairs(int[] arr, int n)
    {
        List<int> v = new List<int>();
 
        // For each element of array.
        for (int i = 0; i < n; i++)
 
            // Try to find the negative value of
            // arr[i] from i + 1 to n
            for (int j = i + 1; j < n; j++)
 
                // If absolute values are equal
                // print pair.
                if (Math.Abs(arr[i]) == Math.Abs(arr[j]))
                    v.Add(Math.Abs(arr[i]));
 
        // If size of vector is 0, therefore there
        // is no element with positive negative
        // value, print "0"
        if (v.Count == 0)
            return;
 
        // Print the pair with negative positive
        // value.
        for (int i = 0; i < v.Count; i++)
            Console.Write(-v[i] + " " + v[i] + " ");
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { 4, 8, 9, -4, 1, -1, -8, -9 };
        int n = arr.Length;
 
        // Function call
        printPairs(arr, n);
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
// Javascript program to find pairs of positive
// and negative values present in an array.
     
    // Print pair with negative and positive value
    function printPairs(arr,n)
    {
        let  v = [];
         
        // For each element of array.
        for (let i = 0; i < n; i++)
  
            // Try to find the negative value of
            // arr[i] from i + 1 to n
            for (let j = i + 1; j < n; j++)
  
                // If absolute values are equal
                // print pair.
                if (Math.abs(arr[i]) ==
                                  Math.abs(arr[j]))
                    v.push(Math.abs(arr[i]));
  
  
        // If size of vector is 0, therefore there
        // is no element with positive negative
        // value, print "0"
        if (v.length == 0)
            return
             
        // Print the pair with negative positive
        // value.
        for (let i = 0; i < v.length; i++)
            document.write(-v[i] + " "
                          + v[i] + " ");
    }
     
    // Driven Program
    let arr=[4, 8, 9, -4, 1, -1, -8, -9];
    let n = arr.length;
    printPairs(arr, n);
     
    // This code is contributed by rag2127
</script>


Output

-4 4 -8 8 -9 9 -1 1 

Time Complexity: O(N2)
Auxiliary Space: O(N)

Find pairs of Positive and Negative values present in given array using hashing:

 To solve the problem follow the below idea:

The idea is to use hashing to store count of absolute value of every element present in the array. If the count of any element is equal to 2, then it means that a pair has been found  

Follow the given steps to solve the problem:

  • Traverse the given array, and increase the count at the absolute value of the hash table. 
  • If the count becomes 2, store its absolute value in another vector. 
  • If the size of the vector is 0, print “0”, 
  • else for each term in the vector print first its negative value and the positive value

Below is the implementation of this approach:

C++




// CPP program to find pairs of
// positive and negative values present in
// an array.
#include <bits/stdc++.h>
using namespace std;
 
// Print pair with negative and positive value
void printPairs(int arr[], int n)
{
    vector<int> v;
    unordered_map<int, bool> cnt;
 
    // For each element of array.
    for (int i = 0; i < n; i++) {
 
        // If element has not encounter early,
        // mark it on cnt array.
        if (cnt[abs(arr[i])] == 0)
            cnt[abs(arr[i])] = 1;
 
        // If seen before, push it in vector (
        // given that elements are distinct)
        else {
            v.push_back(abs(arr[i]));
            cnt[abs(arr[i])] = 0;
        }
    }
 
    if (v.size() == 0)
        return;
 
    for (int i = 0; i < v.size(); i++)
        cout << "-" << v[i] << " " << v[i] << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printPairs(arr, n);
 
    return 0;
}


Java




// Java program to find pairs of
// positive and negative values present in
// an array.
import java.util.*;
class GFG {
 
    // Print pair with negative
    // and positive value
    static void printPairs(int arr[], int n)
    {
        ArrayList<Integer> v = new ArrayList<Integer>();
        HashMap<Integer, Integer> cnt
            = new HashMap<Integer, Integer>();
 
        // For each element of array.
        for (int i = 0; i < n; i++) {
 
            // If element has encounter early,
            // then increment its count
            if (cnt.containsKey(Math.abs(arr[i])))
                cnt.put(Math.abs(arr[i]),
                        cnt.get(Math.abs(arr[i])) + 1);
 
            // If element has not seen before,
            // then initialize its count to 1
            else {
                cnt.put(Math.abs(arr[i]), 1);
            }
            if (cnt.get(Math.abs(arr[i])) == 2) {
                v.add(Math.abs(arr[i]));
            }
        }
        if (v.size() == 0)
            return;
 
        for (int i = 0; i < v.size(); i++)
            System.out.print("-" + v.get(i) + " " + v.get(i)
                             + " ");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
        int n = arr.length;
 
        // Function call
        printPairs(arr, n);
    }
}
// This code is contributed by Prerna Saini


Python3




# Python3 program to find pairs of
# positive and negative values present in
# an array.
# Print pair with negative and
# positive value
 
 
def printPairs(arr, n):
 
    s = set()
    ret = []
 
    # For each element of array.
    for i in arr:
        if abs(i) in s:
            ret.append(abs(i))
        else:
            s.add(abs(i))
 
    ret.sort()
 
    for i in range(0, len(ret)):
        print(-ret[i], "", ret[i], end=" ")
 
 
# Driver Code
if __name__ == "__main__":
    arr = [4, 8, 9, -4, 1, -1, -8, -9]
    n = len(arr)
 
    # Function call
    printPairs(arr, n)
# This code is contributed by RohitOberoi


C#




// C# program to find pairs of
// positive and negative values present in
// an array.
using System;
using System.Collections.Generic;
class GFG {
 
    // Print pair with negative and positive value
    static void printPairs(int[] arr, int n)
    {
        List<int> v = new List<int>();
        Dictionary<int, bool> cnt
            = new Dictionary<int, bool>();
 
        // For each element of array.
        for (int i = 0; i < n; i++) {
 
            // If element has not encounter early,
            // mark it on cnt array.
            int absVal = Math.Abs(arr[i]);
            if (!cnt.ContainsKey(absVal)) {
                cnt[absVal] = true;
            }
            else if (cnt[absVal] == false) {
                cnt[absVal] = true;
            }
            else {
                v.Add(Math.Abs(arr[i]));
                cnt[absVal] = false;
            }
        }
 
        if (v.Count == 0)
            return;
 
        v.Sort();
        for (int i = 0; i < v.Count; i++)
            Console.Write(-v[i] + " " + v[i] + " ");
    }
 
    // Driver code
    static void Main()
    {
        int[] arr = { 4, 8, 9, -4, 1, -1, -8, -9 };
        int n = arr.Length;
 
        // Function call
        printPairs(arr, n);
    }
}
// This code is contributed by divyeshrabadiya07


Javascript




<script>
// JavaScript program to find pairs of
// positive and negative values present in
// an array.
// Print pair with negative and positive value
function printPairs(arr,n)
{
let v = new Array();
let cnt = new Map();
// For each element of array.
for (let i = 0; i < n; i++) {
// If element has not encounter early,
// mark it on cnt array.
if (cnt.has(Math.abs(arr[i])) == false)
cnt.set(Math.abs(arr[i]) , 1);
// If seen before, push it in vector (
// given that elements are distinct)
else {
v.push(Math.abs(arr[i]));
cnt.delete(Math.abs(arr[i]));
}
}
if (v.length == 0)
return;
v.sort((a,b)=>a-b)
for (let i = 0; i < v.length; i++)
document.write(-v[i] + " " + v[i] + " ");
}
// Driven Program
let arr = [ 4, 8, 9, -4, 1, -1, -8, -9 ];
let n = arr.length;
printPairs(arr, n);
// This code is contributed by shinjanpatra.
</script>


Output

-4 4 -1 1 -8 8 -9 9 

Time Complexity: O(N)
Auxiliary Space: O(N)

Find pairs of Positive and Negative values present in given array using set:

To solve the problem follow the below idea:

The idea is to use a set. Find the negative of the number in the set. If it exits then print both the numbers and if it does not exist then add it to the set

Below is the implementation of this approach:

C++




// CPP program to find pairs of
// positive and negative values present in
// an array.
#include <bits/stdc++.h>
using namespace std;
 
// Print pair with negative and positive value
void printPairs(int arr[], int n)
{
    unordered_set<int> hs;
    vector<int> ans;
    for (int i = 0; i < n; i++) {
        if (hs.find((arr[i]) * -1) != hs.end()) {
            if (arr[i] < 0) {
                cout << arr[i] << " ";
                cout << (arr[i] * -1) << " ";
            }
            else {
                cout << (arr[i] * -1) << " ";
                cout << arr[i] << " ";
            }
        }
        hs.insert(arr[i]);
    }
 
    return;
}
 
// Driver code
int main()
{
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printPairs(arr, n);
    return 0;
}


Java




// Java program to find pairs of
// positive and negative values present in
// an array.
import java.util.*;
 
public class GFG {
 
    // Print pair with negative and positive value
    public static void printPairs(int[] arr, int n)
    {
        HashSet<Integer> hs = new HashSet<Integer>();
        ArrayList<Integer> ans = new ArrayList<Integer>();
        for (int i = 0; i < n; i++) {
            if (hs.contains((arr[i]) * -1)) {
                if (arr[i] < 0) {
                    System.out.print(arr[i]);
                    System.out.print(" ");
                    System.out.print((arr[i] * -1));
                    System.out.print(" ");
                }
                else {
                    System.out.print((arr[i] * -1));
                    System.out.print(" ");
                    System.out.print(arr[i]);
                    System.out.print(" ");
                }
            }
 
            hs.add(arr[i]);
        }
 
        return;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 4, 8, 9, -4, 1, -1, -8, -9 };
        int n = arr.length;
 
        // Function call
        printPairs(arr, n);
    }
}
 
// This code is contributed by Aarti_Rathi


Python3




# Python3 program to find pairs of
# positive and negative values present in
# an array
 
 
def printPairs(arr, n):
 
    hs = set()
    ans = []
    for i in range(n):
        if (arr[i] * -1) in hs:
 
            if (arr[i] < 0):
                print(arr[i], end=" ")
                print((arr[i] * -1), end=" ")
 
            else:
                print((arr[i] * -1), end=" ")
                print(arr[i], end=" ")
 
        hs.add(arr[i])
 
    return
 
 
# Driver code
arr = [4, 8, 9, -4, 1, -1, -8, -9]
n = len(arr)
 
# Function call
printPairs(arr, n)
 
# This code is contributed by shinjanpatra.


C#




// C# program to find pairs of positive and
// negative values present in an array.
using System;
using System.Collections;
using System.Collections.Generic;
 
public class GFG {
 
    // Print pair with negative and positive value
    public static void printPairs(int[] arr, int n)
    {
        HashSet<int> hs = new HashSet<int>();
        for (int i = 0; i < n; i++) {
            if (hs.Contains((arr[i]) * -1)) {
                if (arr[i] < 0) {
                    Console.Write(arr[i]);
                    Console.Write(" ");
                    Console.Write((arr[i] * -1));
                    Console.Write(" ");
                }
                else {
                    Console.Write((arr[i] * -1));
                    Console.Write(" ");
                    Console.Write(arr[i]);
                    Console.Write(" ");
                }
            }
            hs.Add(arr[i]);
        }
 
        return;
    }
 
    // Driver code
    static public void Main()
    {
        int[] arr = { 4, 8, 9, -4, 1, -1, -8, -9 };
        int n = arr.Length;
 
        // Function call
        printPairs(arr, n);
    }
}
 
// This code is contributed by lokeshmvs21.


Javascript




<script>
// Efficient JavaScript program to find pairs of
// positive and negative values present in
// an array.
// Print pair with negative and positive value
function printPairs(arr, n)
{
let hs = new Set();
let ans = new Array();
for(let i = 0 ; i < n ; i++ ){
if( hs.has((arr[i])*-1) == true){
if(arr[i] < 0){
document.write(arr[i]," ");
document.write((arr[i]*-1)," ");
}else{
document.write((arr[i]*-1)," ");
document.write(arr[i]," ");
}
}
hs.add(arr[i]) ;
}
 
return ;
}
// Driver Program
let arr = [ 4, 8, 9, -4, 1, -1, -8, -9 ];
let n = arr.length;
printPairs(arr, n);
// This code is contributed by shinjanpatra.
</script>


Output

-4 4 -1 1 -8 8 -9 9 

Time Complexity: O(N)
Auxiliary Space: O(N)

 



Last Updated : 03 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads