Rahul Sharma
Rahul's Blog

Rahul's Blog

Two Pair Sum

Rahul Sharma's photo
Rahul Sharma

Published on Jul 17, 2021

1 min read

Find all the pairs of two integers in an unsorted array that sum up to a given S

#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

vector<int> pairSum(vector<int> arr, int S)
{
    unordered_set<int> s;
    vector<int> result;

    for (int i = 0; i < arr.size(); i++)
    {
        int x = S - arr[i];
        if (s.find(x) != s.end())
        {
            result.push_back(x);
            result.push_back(arr[i]);
            return result;
        }
        s.insert(arr[i]);
    }
    return result;
}

int main()
{
    vector<int> arr = {10, 5, 2, 3, -6, 9, 11};
    int S = 4;

    auto p = pairSum(arr, S);
    if (p.size() == 0)
    {
        cout << "No such pair";
    }
    else
    {
        cout << p[0] << " , " << p[1] << endl;
    }
    return 0;
}
 
Share this