Given a circularly sorted array of integers, find a pair with a given sum. Assume there are no duplicates in the array, and the rotation is in an anti-clockwise direction around an unknown pivot.

For example,

A simple solution would be to consider each pair in the given array and check if the desired sum is found. The problem with this approach is that its worst-case time complexity is O(n2). This solution also does not take advantage of the fact that the array is circularly sorted.

We have already discussed the 2-pointer algorithm to find pairs with a given sum in a sorted array in O(n) time. We can extend this solution for circularly sorted arrays as well. We start by finding out the Pivot element of the sorted sequence, which has a special property which no other element in the array have – both the next and previous element of the pivot element are greater than it.
The idea is to maintain two indices (low and high) that initially points to a minimum and maximum elements in the array. Then loop till low becomes equal to the high index and reduce the search space at each iteration of the loop by comparing the sum of elements present at index low and high with the desired sum. Increment low if the sum is less than the expected sum; otherwise, decrement high if it is more than the desired sum. If the pair is found, return it.
Note that the indices are incremented and decremented in a rotational manner using modular arithmetic since the array is circularly rotated. The complete algorithm is demonstrated below in C, Java, and Python:

C

Download   Run Code

Output:

Pair found (3, 15)

Java

Download   Run Code

Output:

Pair found (3, 15)

Python

Download   Run Code

Output:

Pair found (3, 15)

Download   Run Code
Output:

Pair found (3, 15)

Download   Run Code
Output:

Pair found (3, 15)

Download   Run Code
Output:

Pair found (3, 15)

The time complexity of the above solution is O(n), and the auxiliary space used by the program is O(1).
source