Documente Academic
Documente Profesional
Documente Cultură
Given an array that is sorted and then rotated around an unknown point. Find if array has a pair with given
sum x. It may be assumed that all elements in array are distinct.
Examples:
The idea is to first find the maximum element in array which is the pivot point also and the element just before
maximum is the minimum element. Once we have indexes maximum and minimum elements, we use similar
meet in middle algorithm (as discussed in Given an array A[] and a number x, check for pair in A[] with sum as
x in Searching and Sorting) to find if there is a pair. The only thing new here is indexes are incremented and
decremented in rotational manner using modular arithmetic.
if (pairInSortedRotated(arr, n, sum))
cout << "Array has two elements with sum 16";
else
cout << "Array doesn't have two elements with sum 16 ";
return 0;
}
Output:
Array has two elements with sum 16
Time complexity of the above solution is O(n). The step to find the pivot can be optimized to O(Logn) using the
Binary Search approach discussed in Find the minimum element in a sorted and rotated array in Array
Rotations.
Exercise:
1) Extend the above solution to work for arrays with duplicates allowed.
2) Extend the above solution to find all pairs.