Find pairs in array whose sum does not exist in Array

Given an array arr[] consisting of N positive integers, the task is to print all pairs of array elements whose sum does not exist in the given array. If no such pair exists, print “-1”.
Examples:

Input: arr[] = {2, 4, 2, 6} 
Output: 
(2, 6) 
(4, 6) 
(2, 6) 
Explanation: 
All possible pairs in the array are (2, 4), (2, 2), (2, 6), (4, 2), (4, 6) and (2, 6). 
Among these, the pairs (2, 6), (4, 6) and (2, 6) have sums {8, 10, 8} respectively which are not present in the array.

Input: arr[] = {1, 1, 2, 3} 
Output: 
(2, 3) 
Explanation: 
All possible pairs in the array are (1, 1), (1, 2), (1, 3), (1, 2), (1, 3) and (2, 3). 
Among these, the only pair whose sum is not present in the array is (2, 3).

Naive Approach: 
The simplest approach to solve the problem is to generate all possible pairs one by one, and for every pair check if its sum exists in the array by traversing the array. If any pair is found with its sum existing in the array, print the pair. Otherwise, move to the next pair. 

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

Efficient Approach: 
The problem can be solved using a HashSet. Follow the steps below to solve the problem:



  • Store the elements in the of the array in a HashSet.
  • Now, traverse over all the array elements and generate all possible pairs.
  • For each pair, check if the sum of that pair is present in the HashSet or not. If so, print the pair. Otherwise, move to the next pair.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement 
// the above approach 
#include <bits/stdc++.h> 
using namespace std; 
  
// Function to print all pairs 
// with sum not present in the array 
void findPair(int arr[], int n) 
    int i, j; 
  
    // Corner Case 
    if (n < 2) 
    
        cout << "-1" << endl; 
    
  
    // Stores the distinct array 
    // elements 
    set <int> hashMap; 
  
    for(int k = 0; k < n; k++) 
    
        hashMap.insert(arr[k]); 
    
  
    // Generate all possible pairs 
    for(i = 0; i < n - 1; i++) 
    
        for(j = i + 1; j < n; j++) 
        
              
            // Calculate sum of current pair 
            int sum = arr[i] + arr[j]; 
  
            // Check if the sum exists in 
            // the HashSet or not 
            if (hashMap.find(sum) == hashMap.end()) 
            
      
                cout << "(" << arr[i] << ", "
                    << arr[j] << ")" << endl; 
            
        
    
  
// Driver code 
int main() 
    int arr[] = { 2, 4, 2, 6 }; 
    int n = sizeof(arr) / sizeof(arr[0]); 
  
    findPair(arr, n); 
    return 0; 
  
// This code is contributed by divyeshrabadiya07 

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement 
// the above approach 
import java.util.*; 
  
class GFG { 
  
    // Function to print all pairs 
    // with sum not present in the array 
    public static void findPair( 
        int[] arr, int n) 
    
        int i, j; 
  
        // Corner Case 
        if (n < 2) { 
            System.out.println("-1"); 
        
  
        // Stores the distinct array 
        // elements 
        HashSet<Integer> hashMap 
            = new HashSet<Integer>(); 
  
        for (Integer k : arr) { 
            hashMap.add(k); 
        
  
        // Generate all possible pairs 
        for (i = 0; i < n - 1; i++) { 
  
            for (j = i + 1; j < n; j++) { 
  
                // Calculate sum of current pair 
                int sum = arr[i] + arr[j]; 
  
                // Check if the sum exists in 
                // the HashSet or not 
                if (!hashMap.contains(sum)) { 
  
                    System.out.println( 
                        "(" + arr[i] + ", "
                        + arr[j] + ")"); 
                
            
        
    
  
    // Driver Code 
    public static void main(String[] args) 
    
        int[] arr = { 2, 4, 2, 6 }; 
        int n = arr.length; 
  
        findPair(arr, n); 
    

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement 
# the above approach 
  
# Function to print all pairs 
# with sum not present in the array 
def findPair(arr, n): 
  
    # Corner Case 
    if (n < 2): 
        print("-1"
  
    # Stores the distinct array 
    # elements 
    hashMap = [] 
  
    for k in arr: 
        hashMap.append(k) 
  
    # Generate all possible pairs 
    for i in range (n - 1): 
        for j in range (i + 1, n): 
            # Calculate sum of current pair 
            sum = arr[i] + arr[j] 
  
            # Check if the sum exists in 
            # the HashSet or not 
            if sum not in hashMap: 
                print("(", arr[i] , ", "
                        arr[j] , ")"
  
# Driver Code 
if __name__ == "__main__"
      
    arr = [ 2, 4, 2, 6
    n = len(arr) 
          
    findPair(arr, n) 
  
# This code is contributed by ChitraNayal 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
using System.Collections.Generic; 
  
class GFG{
  
// Function to print all pairs
// with sum not present in the array
public static void findPair(int[] arr, int n)
{
    int i, j;
  
    // Corner Case
    if (n < 2)
    {
        Console.Write("-1");
    }
  
    // Stores the distinct array
    // elements
    HashSet<int> hashMap = new HashSet<int>();
  
    foreach(int k in arr)
    {
        hashMap.Add(k);
    }
  
    // Generate all possible pairs
    for(i = 0; i < n - 1; i++)
    {
        for(j = i + 1; j < n; j++)
        {
              
            // Calculate sum of current pair
            int sum = arr[i] + arr[j];
  
            // Check if the sum exists in
            // the HashSet or not
            if (!hashMap.Contains(sum))
            {
                Console.Write("(" + arr[i] +
                             ", " + arr[j] + 
                             ")\n");
            }
        }
    }
}
  
// Driver Code
public static void Main(string[] args)
{
    int[] arr = { 2, 4, 2, 6 };
    int n = arr.Length;
  
    findPair(arr, n);
}
}
  
// This code is contributed by rutvik_56

chevron_right


Output:

(2, 6)
(4, 6)
(2, 6)

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.