Solved Problem - Pair Sum
We'll cover the following
Problem statement
Given a sorted array of integers . Find if there exist a pair of integers and such that the sum is equal to the given integer .
Input format
The first line of input consists of two space-separated integers and .
The next line contains space-separated integers representing the array .
Output format
Print a single line of two space-separated integers and such that or print if there is no such pair.
Sample
Input
6 14
2 4 7 10 15 16
Output
2 4
Explanation
and element of add upto .
Brute force
Use two loops to iterate over the array and check all pairs. Time complexity is .
Optimization to
Let’s see how we can optimize the time, even more, using pointers. The algorithm is very similar to binary search in terms of how we move the pointers.
We start from the two ends of the sorted array using two pointers lets call the and . The algorithm:
Compare and :
-
If X is equal, we found a pair .
-
If X is greater, move to . This will increase the sum of .
-
If X is smaller, move to . This will decrese the sum of .
Get hands-on with 1400+ tech skills courses.