Find two non-overlapping pairs having equal sum in an Array
Last Updated :
16 Feb, 2023
Given an unsorted array of integers. The task is to find any two non-overlapping pairs whose sum is equal.
Two pairs are said to be non-overlapping if all the elements of the pairs are at different indices. That is, pair (Ai, Aj) and pair (Am, An) are said to be non-overlapping if i ? j ? m ? n.
Examples:
Input: arr[] = {8, 4, 7, 8, 4}
Output: Pair First(4, 8)
Pair Second (8, 4)
Input: arr[] = {8, 4, 7, 4}
Output: No such non-overlapping pairs present.
Note: (8, 4) and (8, 4) forms overlapping pair
as index of 8 is same in both pairs.
The idea is to use a map of key-value pair to store all occurrences of a sum. The key in the map will store the sum and the corresponding value will be a list of pair of indices (i, j) with that sum.
- The idea is to traverse the array and generate all possible pairs.
- If a new sum is found, insert it directly to the map otherwise check if any of the previously encountered pairs with that sum does not overlap with current pair.
- If not, print both of the pairs.
Below is implementation of the above approach:
C++
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
typedef pair< int , int > Pair;
void findPairs( int arr[], int n)
{
unordered_map< int , vector<Pair> > map;
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
int sum = arr[i] + arr[j];
if (map.find(sum) != map.end()) {
for ( auto pair : map.find(sum)->second) {
int m = pair.first, n = pair.second;
if ((m != i && m != j) && (n != i && n != j)) {
cout << "Pair First(" << arr[i] << ", "
<< arr[j] << ")\nPair Second ("
<< arr[m] << ", " << arr[n] << ")" ;
return ;
}
}
}
map[sum].push_back({ i, j });
}
}
cout << "No such non-overlapping pairs present" ;
}
int main()
{
int arr[] = { 8, 4, 7, 8, 4 };
int size = sizeof (arr) / sizeof (arr[0]);
findPairs(arr, size);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Pair {
public int x, y;
Pair( int x, int y)
{
this .x = x;
this .y = y;
}
}
class GFG {
public static void findPairs( int [] A)
{
Map<Integer, List<Pair> > map = new HashMap<>();
for ( int i = 0 ; i < A.length - 1 ; i++) {
for ( int j = i + 1 ; j < A.length; j++) {
int sum = A[i] + A[j];
if (map.containsKey(sum)) {
for (Pair pair : map.get(sum)) {
int x = pair.x;
int y = pair.y;
if ((x != i && x != j) && (y != i && y != j)) {
System.out.println( "Pair First(" + A[i] + ", "
+ A[j] + ")" );
System.out.println( "Pair Second (" + A[x] + ", "
+ A[y] + ")" );
return ;
}
}
}
map.putIfAbsent(sum, new ArrayList<>());
map.get(sum).add( new Pair(i, j));
}
}
System.out.print( "No such non-overlapping pairs present" );
}
public static void main(String[] args)
{
int [] A = { 8 , 4 , 7 , 8 , 4 };
findPairs(A);
}
}
|
Python3
def findPairs(arr, size):
Map = {}
for i in range ( 0 , size - 1 ):
for j in range (i + 1 , size):
Sum = arr[i] + arr[j]
if Sum in Map :
for pair in Map [ Sum ]:
m, n = pair
if ((m ! = i and m ! = j) and
(n ! = i and n ! = j)):
print ( "Pair First ({}, {})" .
format (arr[i], arr[j]))
print ( "Pair Second ({}, {})" .
format (arr[m], arr[n]))
return
if Sum not in Map :
Map [ Sum ] = []
Map [ Sum ].append((i, j))
print ( "No such non-overlapping pairs present" )
if __name__ = = "__main__" :
arr = [ 8 , 4 , 7 , 8 , 4 ]
size = len (arr)
findPairs(arr, size)
|
C#
using System;
using System.Collections.Generic;
class Pair
{
public int x, y;
public Pair( int x, int y)
{
this .x = x;
this .y = y;
}
}
class GFG{
public static void findPairs( int [] A)
{
Dictionary< int ,
List<Pair>> map = new Dictionary< int ,
List<Pair>>();
for ( int i = 0; i < A.Length - 1; i++)
{
for ( int j = i + 1; j < A.Length; j++)
{
int sum = A[i] + A[j];
if (map.ContainsKey(sum))
{
foreach (Pair pair in map[sum])
{
int x = pair.x;
int y = pair.y;
if ((x != i && x != j) &&
(y != i && y != j))
{
Console.WriteLine( "Pair First(" + A[i] +
", " + A[j] + ")" );
Console.WriteLine( "Pair Second (" + A[x] +
", " + A[y] + ")" );
return ;
}
}
}
map[sum] = new List<Pair>();
map[sum].Add( new Pair(i, j));
}
}
Console.Write( "No such non-overlapping pairs present" );
}
public static void Main(String[] args)
{
int [] A = { 8, 4, 7, 8, 4 };
findPairs(A);
}
}
|
Javascript
class Pair {
constructor(x, y) {
this .x = x;
this .y = y;
}
}
function findPairs(A)
{
const map = new Map();
for (let i = 0; i < A.length - 1; i++) {
for (let j = i + 1; j < A.length; j++) {
const sum = A[i] + A[j];
if (map.has(sum)) {
for (const pair of map.get(sum)) {
const x = pair.x;
const y = pair.y;
if ((x !== i && x !== j) && (y !== i && y !== j)) {
console.log(`Pair First(${A[i]}, ${A[j]})`);
console.log(`Pair Second(${A[x]}, ${A[y]})`);
return ;
}
}
}
if (!map.has(sum)) {
map.set(sum, []);
}
map.get(sum).push( new Pair(i, j));
}
}
console.log( "No such non-overlapping pairs present" );
}
const A = [8, 4, 7, 8, 4];
findPairs(A);
|
Output
Pair First(4, 8)
Pair Second (8, 4)
Time Complexity: O(n2)
Auxiliary Space: O(n2)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...