Find Pairs with Given Sum in a Sorted Array – Java Code

Java code to find pairs with given sum in a sorted array. Given an array A of size N. Write a java code to find all pairs in the array that sum to a number equal to K. If no such pair exists then output will be 1.  Array elements are distinct and in a sorted order.

For example –

Input :

arr[] = {1, 2, 3, 4, 5, 6, 7};
sum = 9

Output:

Pairs with given sum 9 is

Pair (2 , 7 )
Pair (3 , 6 )
Pair (4 , 5 )

Find Pairs with Given Sum in a Sorted Array

Find Pairs with Given Sum in a Sorted Array

 

How to Find Pairs with Given Sum in Array

i) To solve this problem, let’s take two indexes low and high and assign a value zero and array length -1.

Subscribe Our Tutorials

Get Latest Updates on Facebook

low = 0, high = arr.length-1

ii) Traverse an array from both the ends and increment the value of low and high based on that.

iii) If we found the pairs with given sum the print the value.

The time complexity of this approach is O(n).

I have explained this approach in this video tutorial.

Find Pairs with Given Sum in a Sorted Array – Java Code

We have discussed the approach, how to find pairs with given sum in an array. Let’s write a java code print all the pairs with given sum in an array.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , . Bookmark the permalink.