
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Four Elements A, B, C, and D in an Array Such That A + B = C + D in C++
Suppose we have a list of integers. Our task is to find four distinct integers as two pairs like (a, b) and (c, d), such that a+b = c+d. If there are multiple answers, then print only one. Suppose the array elements are like: A = [7, 5, 9, 3, 6, 4, 2], then pairs can be (7, 3) and (6, 4)
Here we will use the hashing technique. We use the sum as key as pair as the value in the hash table. We have to follow these steps to solve this problem.
- For i in range 0 to n – 1, do
- for j in range i + 1 to n – 1, do
- find the sum
- If the hash table has the sum already, then print the previous pair and the current pair
- Otherwise, update the hash table.
- for j in range i + 1 to n – 1, do
Example
#include<iostream> #include<map> using namespace std; bool getTwoPairs(int arr[], int n) { map<int, pair<int, int> > hash_table; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { int sum = arr[i] + arr[j]; if (hash_table.find(sum) == hash_table.end()) hash_table[sum] = make_pair(i, j); else { pair<int, int> pp = hash_table[sum]; cout << "(" << arr[pp.first] << " + " << arr[pp.second] << ") = (" << arr[i] << " + " << arr[j] << ")"; return true; } } } cout << "No pairs found"; return false; } int main() { int arr[] = {7, 5, 9, 3, 6, 4, 2}; int n = sizeof arr / sizeof arr[0]; cout << "The pairs are: "; getTwoPairs(arr, n); }
Output
The pairs are: (7 + 4) = (5 + 6)
Advertisements