Getting a Pair whose Sum = K
Obtaining a pair of elements in the array whose sum = k.
For Sorted Arrays:
void findPair(int a[], int n, int key) {
// Set i to starting index and j to last index
int i = 0, j = n-1;
while (i < j) {
// If pair is found, increment i and decrement j
if (a[i] + a[j] == key) {
printf("Pair : %d and %d\n", a[i], a[j]);
i++;
j--;
}
// If sum is greater than key, decrement j
else if (a[i] + a[j] > key) {
j--;
}
// If sum is smaller than key, increment i
else {
i++;
}
}
}For Unsorted Arrays:
Contributed by Nitin Ranganath
Last updated
Was this helpful?