-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathPair_with_given_sum.c
More file actions
84 lines (65 loc) · 1.58 KB
/
Pair_with_given_sum.c
File metadata and controls
84 lines (65 loc) · 1.58 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//Method 1:
#include <stdio.h>
// Naive method to find a pair in an array with given sum
void findPair(int arr[], int n, int sum)
{
// consider each element except last element
for (int i = 0; i < n - 1; i++)
{
// start from i'th element till last element
for (int j = i + 1; j < n; j++)
{
// if desired sum is found, print it and return
if (arr[i] + arr[j] == sum)
{
printf("Pair found at index %d and %d", i, j);
return;
}
}
}
// No pair with given sum exists in the array
printf("Pair not found");
}
// Find pair with given sum in the array
int main()
{
int arr[] = { 8, 7, 2, 5, 3, 1 };
int sum = 10;
int n = sizeof(arr)/sizeof(arr[0]);
findPair(arr, n, sum);
return 0;
}
//Method 2: O(n) Solution using Hashing
#include <iostream>
#include <unordered_map>
// Function to find a pair in an array with given sum using Hashing
void findPair(int arr[], int n, int sum)
{
// create an empty map
std::unordered_map<int, int> map;
// do for each element
for (int i = 0; i < n; i++)
{
// check if pair (arr[i], sum-arr[i]) exists
// if difference is seen before, print the pair
if (map.find(sum - arr[i]) != map.end())
{
std::cout << "Pair found at index " << map[sum - arr[i]] <<
" and " << i;
return;
}
// store index of current element in the map
map[arr[i]] = i;
}
// we reach here if pair is not found
std::cout << "Pair not found";
}
// Find pair with given sum in the array
int main()
{
int arr[] = { 8, 7, 2, 5, 3, 1};
int sum = 10;
int n = sizeof(arr)/sizeof(arr[0]);
findPair(arr, n, sum);
return 0;
}