-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
find_pairs_with_sum.cpp
48 lines (43 loc) · 1.17 KB
/
find_pairs_with_sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* Problem:
* Given an unsorted array of integers, find a pair with given sum in it.
* For example,
* Input:
* arr = [8, 7, 2, 5, 3, 1]
* sum = 10
*
* Output:
* Pair found at index 0 and 2 (8 + 2)
* OR
* Pair found at index 1 and 4 (7 + 3)
*/
#include <iostream>
#include <vector>
#include <unordered_map>
void printPairWithSum(const std::vector<int>& arr, const int sum)
{
std::unordered_map<int, int> hashMap;
bool found = false;
for (unsigned int i = 0; i < arr.size(); ++i)
{
// We need to check if pair(arr[i], sum-arr[i]) already
// exists in the map
//
if (hashMap.find(sum-arr[i]) != hashMap.end())
{
std::cout << "Found pair with sum: " << sum
<< " with values (" << sum-arr[i] << " ," << arr[i]
<< ") at indices (" << hashMap[sum-arr[i]] << " ,"
<< i << ")" << std::endl;
found = true;
}
hashMap[arr[i]] = i;
}
if (!found) std::cout << "Pair not found\n";
}
int main()
{
std::vector<int> arr {8, 7, 2, 5, 3, 1};
printPairWithSum(arr, 10);
return 0;
}