Skip to content

Commit 631368b

Browse files
committed
Pairs with sum in an array
1 parent 162e034 commit 631368b

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <bits/stdc++.h>
2+
3+
4+
void printPairWithSum(const std::vector<int>& arr, const int sum)
5+
{
6+
std::unordered_map<int, int> hashMap;
7+
bool found = false;
8+
for (unsigned int i = 0; i < arr.size(); ++i)
9+
{
10+
// We need to check if pair(arr[i], sum-arr[i]) already
11+
// exists in the map
12+
//
13+
if (hashMap.find(sum-arr[i]) != hashMap.end())
14+
{
15+
std::cout << "Found pair with sum: " << sum
16+
<< " with values (" << sum-arr[i] << " ," << arr[i]
17+
<< ") at indices (" << hashMap[sum-arr[i]] << " ,"
18+
<< i << ")" << std::endl;
19+
found = true;
20+
}
21+
hashMap[arr[i]] = i;
22+
}
23+
if (!found) std::cout << "Pair not found\n";
24+
}
25+
26+
int main()
27+
{
28+
std::vector<int> arr {8, 7, 2, 5, 3, 1};
29+
printPairWithSum(arr, 10);
30+
return 0;
31+
}

0 commit comments

Comments
 (0)