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++
// C++ programs to find two non-overlapping
// pairs having equal sum in an Array
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
typedef pair<int, int> Pair;
// Function to find two non-overlapping
// with same sum in an array
void findPairs(int arr[], int n)
{
// first create an empty map
// key -> which is sum of a pair of
// elements in the array
// value -> vector storing index of
// every pair having that sum
unordered_map<int, vector<Pair> > map;
// consider every pair (arr[i], arr[j])
// and where (j > i)
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// calculate sum of current pair
int sum = arr[i] + arr[j];
// if sum is already present in the map
if (map.find(sum) != map.end()) {
// check every pair having equal sum
for (auto pair : map.find(sum)->second) {
int m = pair.first, n = pair.second;
// if pairs don't overlap,
// print them and return
if ((m != i && m != j) && (n != i && n != j)) {
cout << "Pair First(" << arr[i] << ", "
<< arr[j] << ")\nPair Second ("
<< arr[m] << ", " << arr[n] << ")";
return;
}
}
}
// Insert current pair into the map
map[sum].push_back({ i, j });
}
}
// If no such pair found
cout << "No such non-overlapping pairs present";
}
// Driver Code
int main()
{
int arr[] = { 8, 4, 7, 8, 4 };
int size = sizeof(arr) / sizeof(arr[0]);
findPairs(arr, size);
return 0;
}
Java
// Java program to find two non-overlapping
// pairs having equal sum in an Array
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// Declare a pair
class Pair {
public int x, y;
Pair(int x, int y)
{
this.x = x;
this.y = y;
}
}
class GFG {
// Function to find two non-overlapping
// pairs with same sum in an array
public static void findPairs(int[] A)
{
// first create an empty map
// key -> which is sum of a pair
// of elements in the array
// value -> list storing index of
// every pair having that sum
Map<Integer, List<Pair> > map = new HashMap<>();
// consider every pair (A[i], A[j]) where (j > i)
for (int i = 0; i < A.length - 1; i++) {
for (int j = i + 1; j < A.length; j++) {
// calculate sum of current pair
int sum = A[i] + A[j];
// if sum is already present in the map
if (map.containsKey(sum)) {
// check every pair having desired sum
for (Pair pair : map.get(sum)) {
int x = pair.x;
int y = pair.y;
// if pairs don't overlap, print
// them and return
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;
}
}
}
// Insert current pair into the map
map.putIfAbsent(sum, new ArrayList<>());
map.get(sum).add(new Pair(i, j));
}
}
System.out.print("No such non-overlapping pairs present");
}
// Driver Code
public static void main(String[] args)
{
int[] A = { 8, 4, 7, 8, 4 };
findPairs(A);
}
}
Python3
# Python3 programs to find two non-overlapping
# pairs having equal Sum in an Array
# Function to find two non-overlapping
# with same Sum in an array
def findPairs(arr, size):
# first create an empty Map
# key -> which is Sum of a pair of
# elements in the array
# value -> vector storing index of
# every pair having that Sum
Map = {}
# consider every pair (arr[i], arr[j])
# and where (j > i)
for i in range(0, size - 1):
for j in range(i + 1, size):
# calculate Sum of current pair
Sum = arr[i] + arr[j]
# if Sum is already present in the Map
if Sum in Map:
# check every pair having equal Sum
for pair in Map[Sum]:
m, n = pair
# if pairs don't overlap,
# print them and return
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
# Insert current pair into the Map
if Sum not in Map:
Map[Sum] = []
Map[Sum].append((i, j))
# If no such pair found
print("No such non-overlapping pairs present")
# Driver Code
if __name__ == "__main__":
arr = [8, 4, 7, 8, 4]
size = len(arr)
findPairs(arr, size)
# This code is contributed by Rituraj Jain
C#
// C# program to find two non-overlapping
// pairs having equal sum in an Array
using System;
using System.Collections.Generic;
// Declare a pair
class Pair
{
public int x, y;
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
}
class GFG{
// Function to find two non-overlapping
// pairs with same sum in an array
public static void findPairs(int[] A)
{
// First create an empty map
// key -> which is sum of a pair
// of elements in the array
// value -> list storing index of
// every pair having that sum
Dictionary<int,
List<Pair>> map = new Dictionary<int,
List<Pair>>();
// Consider every pair (A[i], A[j])
// where (j > i)
for(int i = 0; i < A.Length - 1; i++)
{
for(int j = i + 1; j < A.Length; j++)
{
// Calculate sum of current pair
int sum = A[i] + A[j];
// If sum is already present in the map
if (map.ContainsKey(sum))
{
// Check every pair having desired sum
foreach(Pair pair in map[sum])
{
int x = pair.x;
int y = pair.y;
// If pairs don't overlap, print
// them and return
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;
}
}
}
// Insert current pair into the map
map[sum] = new List<Pair>();
map[sum].Add(new Pair(i, j));
}
}
Console.Write("No such non-overlapping pairs present");
}
// Driver Code
public static void Main(String[] args)
{
int[] A = { 8, 4, 7, 8, 4 };
findPairs(A);
}
}
// This code is contributed by Princi Singh
JavaScript
// Declare a pair
class Pair {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
// Function to find two non-overlapping
// pairs with same sum in an array
function findPairs(A)
{
// first create an empty map
// key -> which is sum of a pair
// of elements in the array
// value -> list storing index of
// every pair having that sum
const map = new Map();
// consider every pair (A[i], A[j]) where (j > i)
for (let i = 0; i < A.length - 1; i++) {
for (let j = i + 1; j < A.length; j++) {
// calculate sum of current pair
const sum = A[i] + A[j];
// if sum is already present in the map
if (map.has(sum)) {
// check every pair having desired sum
for (const pair of map.get(sum)) {
const x = pair.x;
const y = pair.y;
// if pairs don't overlap, print
// them and return
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;
}
}
}
// Insert current pair into the map
if (!map.has(sum)) {
map.set(sum, []);
}
map.get(sum).push(new Pair(i, j));
}
}
console.log("No such non-overlapping pairs present");
}
// Driver Code
const A = [8, 4, 7, 8, 4];
findPairs(A);
// This code is contributed by phasing17.
OutputPair First(4, 8)
Pair Second (8, 4)
Time Complexity: O(n2)
Auxiliary Space: O(n2)
Similar Reads
Find the overlapping sum of two arrays Given two arrays A[] and B[] having n unique elements each. The task is to find the overlapping sum of the two arrays. That is the sum of elements that is common in both of the arrays. Note: Elements in the arrays are unique. That is the array does not contain duplicates. Examples: Input : A[] = {1,
8 min read
Count pairs from two arrays having sum equal to K Given an integer K and two arrays A1 and A2, the task is to return the total number of pairs (one element from A1 and one element from A2) with a sum equal to K. Note: Arrays can have duplicate elements. We consider every pair as different, the only constraint is, an element (of any array) can parti
6 min read
Count pairs in given Array having sum of index and value at that index equal Given an array arr[] containing positive integers, count the total number of pairs for which arr[i]+i = arr[j]+j such that 0â¤i<jâ¤n-1. Examples: Input: arr[] = { 6, 1, 4, 3 }Output: 3Explanation: The elements at index 0, 2, 3 has same value of a[i]+i as all sum to 6 {(6+0), (4+2), (3+3)}. Input: a
8 min read
Sum of f(a[i], a[j]) over all pairs in an array of n integers Given an array of n integers, find the sum of f(a[i], a[j]) of all pairs (i, j) such that (1 <= i < j <= n). f(a[i], a[j]): If |a[j]-a[i]| > 1 f(a[i], a[j]) = a[j] - a[i] Else // if |a[j]-a[i]| <= 1 f(a[i], a[j]) = 0 Examples: Input : 6 6 4 4 Output : -8 Explanation: All pairs are: (6
8 min read
Maximum Count of pairs having equal Sum based on the given conditions Given an array arr[] of length N containing array elements in the range [1, N], the task is to find the maximum number of pairs having equal sum, given that any element from the array can only be part of a single pair. Examples: Input: arr[] = {1, 4, 1, 4} Output: 2 Explanation: Pairs {{1, 4}, {1, 4
8 min read
Find pairs in array whose sums already exist in array Given an array of n distinct and positive elements, the task is to find pair whose sum already exists in the given array. Examples : Input : arr[] = {2, 8, 7, 1, 5};Output : 2 5 7 1 Input : arr[] = {7, 8, 5, 9, 11};Output : Not ExistA Naive Approach is to run three loops to find pair whose sum exist
9 min read