
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print all pairs in an unsorted array with equal sum in C++
In this problem, we have an unsorted array and we have to print all pairs within this array that have an equal sum.
Let’s take an example to understand the problem −
Input: array = [12, 13, 20, 5] Output: [12, 13] and [20, 5] have sum 25.
To solve this problem, we will have to find pairs of the same sum. For this, we will check pairs for the same sum. And to avoid duplicate pairs, we will use the map.
For this, we will need two maps, one to store all sum pairs and their sum and others to store all sum and their corresponding pairs.
So, Map1 → key = pairs; value → sum
Map2 → key = sum integer; value → vector of pair
Now, print all values that have the same sum value.
Example
Program to illustrate the above logic −
#include <bits/stdc++.h> using namespace std; void findEqualSumPairs(int A[], int n){ map<int, vector<pair<int, int> > >map1; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { pair<int, int> p = make_pair(A[i], A[j]); map1[A[i] + A[j]].push_back(p); } } for (auto value = map1.begin(); value != map1.end(); value++) { if (value->second.size() > 1) { for (int i = 0; i < value->second.size(); i++) { cout<<"[ "<<value->second[i].first<<", "<<value->second[i].second<<"] "; } cout<<"have sum : "<<value->first<<endl; } } } int main() { int A[] = { 6, 4, 12, 10, 22,11, 8, 2 }; int n = sizeof(A) / sizeof(A[0]); cout<<"Pairs with same sum are : \n"; findEqualSumPairs(A, n); return 0; }
Output
Pairs with same sum are −
[ 6, 4] [ 8, 2] have sum : 10 [ 4, 8] [ 10, 2] have sum : 12 [ 6, 8] [ 4, 10] [ 12, 2] have sum : 14 [ 6, 10] [ 4, 12] have sum : 16 [ 6, 12] [ 10, 8] have sum : 18
- Related Questions & Answers
- Print all pairs with given sum in C++
- Sum of XOR of all pairs in an array in C++
- Sum of XOR of sum of all pairs in an array in C++
- Count of index pairs with equal elements in an array in C++
- Find the largest pair sum in an unsorted array in C++
- Split Array with Equal Sum in C++
- Count all distinct pairs with difference equal to k in C++
- Print all triplets with given sum in C++
- Print all subarrays with 0 sum in C++
- Print all the sum pairs which occur maximum number of times in C++
- Print all pairs of anagrams in a given array of strings in C++
- Find all the pairs with given sum in a BST in C++
- Find all distinct pairs with difference equal to k in Python
- Count pairs with given sum in C++
- Print triplets with sum less than or equal to k in C Program
Advertisements