Open In App

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

Last Updated : 30 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Define an array of integers
arr = [1, -3, 2, 3, 6, -1]
 
# Get the length of the array
n = len(arr)
 
# Loop over all pairs of elements in the array
for i in range(n):
    for j in range(i + 1, n):
        # Check if the elements have opposite signs and equal absolute values
        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]))):
            # Print the pair of elements to the console
            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)
    {
        // Define an array of integers
        int[] arr = { 1, -3, 2, 3, 6, -1 };
 
        // Get the length of the array
        int n = arr.Length;
 
        // Loop over all pairs of elements in the array
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                // Check if the elements have opposite signs and equal absolute values
                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])))
                {
                    // Print the pair of elements to the console
                    if (arr[i] < 0)
                    {
                        Console.WriteLine(arr[i] + " " + arr[j]);
                    }
                    else
                    {
                        Console.WriteLine(arr[j] + " " + arr[i]);
                    }
                }
            }
        }
    }
}
// This code is contributed by shivamgupta310570


Javascript




// Define an array of integers
const arr = [1, -3, 2, 3, 6, -1];
 
// Get the length of the array
const n = arr.length;
 
// Loop over all pairs of elements in the array
for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
        // Check if the elements have opposite signs and equal absolute values
        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]))) {
            // Print the pair of elements to the console
            if (arr[i] < 0) {
                console.log(arr[i], arr[j]);
            } else {
                console.log(arr[j], arr[i]);
            }
        }
    }
}
 
// This code is contributed by shivamgupta310570


Output

-1 1
-3 3




 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++




// CPP program to find pairs of positive
// and negative values present in an array.
#include <bits/stdc++.h>
using namespace std;
 
void printPairs(int arr[], int n)
{
    bool pair_exists = false;
    // Sort the array
    sort(arr, arr + n);
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // For every arr[i] < 0 element,
        // do a binary search for arr[i] > 0.
        if (arr[i] < 0) {
 
            // If found, print the pair.
            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";
}
 
// Driver code
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




// Java program to find pairs
// of positive and negative
// values present in an array.
import java.util.*;
class GFG
{
static void printPairs(int arr[], int n)
{
    boolean pair_exists = false;
     
    // Sort the array
    Arrays.sort(arr);
 
    // Traverse the array
    for (int i = 0; i < n; i++)
    {
 
        // For every arr[i] < 0 element,
        // do a binary search for arr[i] > 0.
        if (arr[i] < 0)
        {
 
            // If found, print the pair.
            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");
}
 
// Driver code
public static void main(String args[])
{
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n =arr.length;
 
    printPairs(arr, n);
}
}
 
// This code is contributed
// by Arnab Kundu


Python 3




# Python3 program to find pairs of positive
# and negative values present in an array.
 
# function for binary search
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
    # Sort the array
    arr.sort()
 
    # Traverse the array
    for i in range(n):
     
 
        # For every arr[i] < 0 element,
        # do a binary search for arr[i] > 0.
        if (arr[i] < 0):
 
            # If found, print the pair.
            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")
 
 
# Driver code
if __name__=='__main__':
    arr = [ 4, 8, 9, -4, 1, -1, -8, -9 ]
    n = len(arr)
 
    printPairs(arr, n)
     
# this code is contributed by ash264


C#




// C# program to find pairs
// of positive and negative
// values present in an array.
 
using System;
public class GFG{
 
static void printPairs(int []arr, int n)
{
    bool pair_exists = false;
     
    // Sort the array
    Array.Sort(arr);
 
    // Traverse the array
    for (int i = 0; i < n; i++)
    {
 
        // For every arr[i] < 0 element,
        // do a binary search for arr[i] > 0.
        if (arr[i] < 0)
        {
 
            // If found, print the pair.
            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");
}
 
// Driver code
public static void Main()
{
    int []arr = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n =arr.Length;
 
    printPairs(arr, n);
}
}
 
 
// This code is contributed by 29AjayKumar


Javascript




// JavaScript program to find pairs of positive
// and negative values present in an array.
 
 
function printPairs(arr, n) {
    let pair_exists = false;
    // Sort the array
    arr.sort((a, b) => a - b);
 
    // Traverse the array
    for (let i = 0; i < n; i++) {
 
        // For every arr[i] < 0 element,
        // do a binary search for arr[i] > 0.
        if (arr[i] < 0) {
 
            // If found, print the pair.
            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");
}
 
// Driver code
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++




// CPP program to find pairs of positive
// and negative values present in an array
#include <bits/stdc++.h>
using namespace std;
 
// Function to print pairs of positive
// and negative values present in the array
void printPairs(int arr[], int n)
{
    unordered_set<int> pairs;
    bool pair_exists = false;
 
    // Store all the positive elements
    // in the unordered_set
    for (int i = 0; i < n; i++)
        if (arr[i] > 0)
            pairs.insert(arr[i]);
 
    // Start traversing the array
    for (int i = 0; i < n; i++) {
 
        // Check if the positive value of current
        // element exists in the set or not
        if (arr[i] < 0)
            if (pairs.find(-arr[i]) != pairs.end())
 
            { // Print that pair
                cout << arr[i] << ", " << -arr[i] << endl;
 
                pair_exists = true;
            }
    }
 
    if (pair_exists == false)
        cout << "No such pair exists";
}
 
// Driver code
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




// Java program to find pairs of positive
// and negative values present in an array
import java.util.*;
class GFG
{
 
// Function to print pairs of positive
// and negative values present in the array
static void printPairs(int arr[], int n)
{
    Set<Integer> pairs = new HashSet<Integer>();
    boolean pair_exists = false;
 
    // Store all the positive elements
    // in the unordered_set
    for (int i = 0; i < n; i++)
        if (arr[i] > 0)
            pairs.add(arr[i]);
 
    // Start traversing the array
    for (int i = 0; i < n; i++)
    {
 
        // Check if the positive value of current
        // element exists in the set or not
        if (arr[i] < 0)
            if (pairs.contains(-arr[i]))
            {
                // Print that pair
                System.out.println(arr[i] + ", " + -arr[i]);
 
                pair_exists = true;
            }
    }
 
    if (pair_exists == false)
        System.out.println("No such pair exists");
}
 
// Driver code
public static void main(String args[])
{
    int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n = arr.length;
 
    printPairs(arr, n);
}
}
 
// This code is contributed by Arnab Kundu


Python3




# Python3 program to find pairs of positive
# and negative values present in an array
 
# Function to print pairs of positive
# and negative values present in the array
def printPairs(arr, n):
 
    pairs = set()
    pair_exists = False
 
    # Store all the positive elements
    # in the unordered_set
    for i in range(0, n):
        if arr[i] > 0:
            pairs.add(arr[i])
 
    # Start traversing the array
    for i in range(0, n):
 
        # Check if the positive value of current
        # element exists in the set or not
        if arr[i] < 0:
            if (-arr[i]) in pairs:
 
            # Print that pair
                print("{}, {}".format(arr[i], -arr[i]))
                pair_exists = True
 
    if pair_exists == False:
        print("No such pair exists")
 
# Driver code
if __name__ == "__main__":
 
    arr = [4, 8, 9, -4, 1, -1, -8, -9]
    n = len(arr)
 
    printPairs(arr, n)
 
# This code is contributed by Rituraj Jain


C#




// C# program to find pairs of positive
// and negative values present in an array
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to print pairs of positive
// and negative values present in the array
static void printPairs(int []arr, int n)
{
    HashSet<int> pairs = new HashSet<int>();
    bool pair_exists = false;
 
    // Store all the positive elements
    // in the unordered_set
    for (int i = 0; i < n; i++)
        if (arr[i] > 0)
            pairs.Add(arr[i]);
 
    // Start traversing the array
    for (int i = 0; i < n; i++)
    {
 
        // Check if the positive value of current
        // element exists in the set or not
        if (arr[i] < 0)
            if (pairs.Contains(-arr[i]))
            {
                // Print that pair
                Console.WriteLine(arr[i] + ", " + -arr[i]);
 
                pair_exists = true;
            }
    }
 
    if (pair_exists == false)
        Console.WriteLine("No such pair exists");
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = { 4, 8, 9, -4, 1, -1, -8, -9 };
    int n = arr.Length;
 
    printPairs(arr, n);
}
}
 
// This code is contributed by PrinciRaj1992


Javascript




<script>
 
// JavaScript program to find pairs of positive
// and negative values present in an array
 
// Function to print pairs of positive
// and negative values present in the array
function printPairs(arr,n)
{
    let pairs = new Set();
    let pair_exists = false;
  
    // Store all the positive elements
    // in the unordered_set
    for (let i = 0; i < n; i++)
        if (arr[i] > 0)
            pairs.add(arr[i]);
  
    // Start traversing the array
    for (let i = 0; i < n; i++)
    {
  
        // Check if the positive value of current
        // element exists in the set or not
        if (arr[i] < 0)
            if (pairs.has(-arr[i]))
            {
                // Print that pair
                document.write(arr[i] + ", " + -arr[i]+"<br>");
  
                pair_exists = true;
            }
    }
  
    if (pair_exists == false)
        document.write("No such pair exists");
}
 
// Driver code
let arr=[4, 8, 9, -4, 1, -1, -8, -9];
let n = arr.length;
printPairs(arr, n);
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output

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




Time Complexity: O(n)
Auxiliary Space: O(n) because using unordered_set



Similar Reads

Find pairs of Positive and Negative values present in given array
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 PracticePositive Negative Pai
14 min read
Find the last positive element remaining after repeated subtractions of smallest positive element from all Array elements
Given an array arr[] consisting of N positive integers, the task is to find the last positive array element remaining after repeated subtractions of the smallest positive array element from all array elements. Examples: Input: arr[] = {3, 5, 4, 7}Output: 2Explanation: Subtract the smallest positive element from the array, i.e. 3, the new array is a
6 min read
Only integer with positive value in positive negative value in array
Given an array of N integers. In the given, for each positive element 'x' there exist a negative value '-x', except one integer whose negative value is not present. That integer may occur multiple number of time. The task is find that integer. Examples: Input : arr[] = { 1, 8, -6, -1, 6, 8, 8 } Output : 8 All positive elements have an equal negativ
8 min read
Replace all elements by difference of sums of positive and negative numbers after that element
Given an array of positive and negative elements. The task is to replace every i-th element of the array by the absolute difference of absolute sums of positive and negative elements in the range i+1 to N. That is, find the absolute sum of all positive elements and the absolute sum of all negative elements in the range i+1 to N. Now find the absolu
12 min read
Largest number having both positive and negative values present in the array
Given an array arr[] consisting of N integers, the task is to find the largest number K (&gt; 0) such that both the values K and -K are present in the given array arr[]. If no such number exists, then print -1. Examples: Input: arr[] = {3, 2, -2, 5, -3}Output: 3 Input: arr[] = {1, 2, 3, -4}Output: -1 Naive Approach: The simplest approach to solve t
14 min read
Total Negative and Positive Product Array Pairs
Given an array arr[] of size n, the task is to calculate two following values: Number of pairs [l,r] such that product of all the element from indices l to r is negative.Number of pairs [l,r] such that product of all the element from indices l to r is positive.Example: Input: n = 5, A = { 5, -3, 3, -1, 1 }Output: 8 7 Input: n = 10, A = {4, 2, -4, 3
8 min read
Move all negative numbers to beginning and positive to end with constant extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers. Examples : Input: -12, 11, -13, -5, 6, -7, 5, -3, -6Output: -12 -13 -5 -7 -3 -6 11 6 5 Note: Order of elements is not important here. Naive approach: The idea is to sort the array of ele
21 min read
Count ways to obtain triplets with positive product consisting of at most one negative element
Given an array arr[] of size N (1 ? N ? 105), the task is to find the number of ways to select triplet i, j, and k such that i &lt; j &lt; k and the product arr[i] * arr[j] * arr[k] is positive. Note: Each triplet can consist of at most one negative element. Examples: Input: arr[] = {2, 5, -9, -3, 6} Output: 1 Explanation: The total number ways to
5 min read
Segregating negative and positive maintaining order and O(1) space
Segregation of negative and positive numbers in an array without using extra space, and maintaining insertion order and in O(n^2) time complexity. Examples: Input :9 12 11 -13 -5 6 -7 5 -3 -6 Output :-13 -5 -7 -3 -6 12 11 6 5 Input :5 11 -13 6 -7 5 Output :-13 -7 11 6 5 We have discussed this problem below posts. ers-beginning-positive-end-constant
7 min read
Java Program for Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in t
3 min read
Article Tags :
Practice Tags :