Given a sorted and rotated array, find if there is a pair with a given sum

22 Jun, 2022
Given an array that is sorted and then rotated around an unknown point. Find if the array has a pair with a given sum ‘x’. It may be assumed that all elements in the array are distinct.
Examples : 
Input: arr[] = {11, 15, 6, 8, 9, 10}, x = 16
Output: true
There is a pair (6, 10) with sum 16

Input: arr[] = {11, 15, 26, 38, 9, 10}, x = 35
Output: true
There is a pair (26, 9) with sum 35

Input: arr[] = {11, 15, 26, 38, 9, 10}, x = 45
Output: false
There is no pair with sum 45.
We have discussed a O(n) solution for a sorted array (See steps 2, 3 and 4 of Method 1). We can extend this solution for rotated array as well. The idea is to first find the largest element in array which is the pivot point also and the element just after largest is the smallest element. Once we have indexes largest and smallest elements, we use similar meet in middle algorithm (as discussed here in method 1) to find if there is a pair. The only thing new here is indexes are incremented and decremented in rotational manner using modular arithmetic.
Following is the implementation of above idea.  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find a pair with a given sum in a sorted and// rotated array#include<iostream>using namespace std; // This function returns true if arr[0..n-1] has a pair// with sum equals to x.bool pairInSortedRotated(int arr[], int n, int x){    // Find the pivot element    int i;    for (i=0; i<n-1; i++)        if (arr[i] > arr[i+1])            break;    int l = (i+1)%n;  // l is now index of smallest element    int r = i;        // r is now index of largest element     // Keep moving either l or r till they meet    while (l != r)    {         // If we find a pair with sum x, we return true         if (arr[l] + arr[r] == x)              return true;          // If current pair sum is less, move to the higher sum         if (arr[l] + arr[r] < x)              l = (l + 1)%n;         else  // Move to the lower sum side              r = (n + r - 1)%n;    }    return false;} /* Driver program to test above function */int main(){    int arr[] = {11, 15, 6, 8, 9, 10};    int sum = 16;    int n = sizeof(arr)/sizeof(arr[0]);     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;}
// Java program to find a pair with a given// sum in a sorted and rotated arrayclass PairInSortedRotated{    // This function returns true if arr[0..n-1]    // has a pair with sum equals to x.    static boolean pairInSortedRotated(int arr[],                                    int n, int x)    {        // Find the pivot element        int i;        for (i = 0; i < n - 1; i++)            if (arr[i] > arr[i+1])                break;                         int l = (i + 1) % n; // l is now index of                                                                     // smallest element                                  int r = i;       // r is now index of largest                         //element              // Keep moving either l or r till they meet        while (l != r)        {             // If we find a pair with sum x, we             // return true             if (arr[l] + arr[r] == x)                  return true;                   // If current pair sum is less, move             // to the higher sum             if (arr[l] + arr[r] < x)                  l = (l + 1) % n;                                else  // Move to the lower sum side                  r = (n + r - 1) % n;        }        return false;    }     /* Driver program to test above function */    public static void main (String[] args)    {        int arr[] = {11, 15, 6, 8, 9, 10};        int sum = 16;        int n = arr.length;              if (pairInSortedRotated(arr, n, sum))            System.out.print("Array has two elements" +                             " with sum 16");        else            System.out.print("Array doesn't have two" +                             " elements with sum 16 ");    }}/*This code is contributed by Prakriti Gupta*/
# Python3 program to find a# pair with a given sum in# a sorted and rotated array  # This function returns True# if arr[0..n-1] has a pair# with sum equals to x.def pairInSortedRotated( arr, n, x ):         # Find the pivot element    for i in range(0, n - 1):        if (arr[i] > arr[i + 1]):            break;                 # l is now index of smallest element           l = (i + 1) % n    # r is now index of largest element    r = i         # Keep moving either l    # or r till they meet    while (l != r):                 # If we find a pair with        # sum x, we return True        if (arr[l] + arr[r] == x):            return True;                     # If current pair sum is less,        # move to the higher sum        if (arr[l] + arr[r] < x):            l = (l + 1) % n;        else:                         # Move to the lower sum side            r = (n + r - 1) % n;         return False;  # Driver program to test above functionarr = [11, 15, 6, 8, 9, 10]sum = 16n = len(arr) if (pairInSortedRotated(arr, n, sum)):    print ("Array has two elements with sum 16")else:    print ("Array doesn't have two elements with sum 16 ")      # This article contributed by saloni1297
// C# program to find a pair with a given// sum in a sorted and rotated arrayusing System; class PairInSortedRotated{    // This function returns true if arr[0..n-1]    // has a pair with sum equals to x.    static bool pairInSortedRotated(int []arr,                                    int n, int x)    {        // Find the pivot element        int i;        for (i = 0; i < n - 1; i++)            if (arr[i] > arr[i + 1])                break;                         // l is now index of smallest element               int l = (i + 1) % n;                 // r is now index of largest element                       int r = i;             // Keep moving either l or r till they meet        while (l != r)        {            // If we find a pair with sum x, we            // return true            if (arr[l] + arr[r] == x)                return true;                 // If current pair sum is less,             // move to the higher sum            if (arr[l] + arr[r] < x)                l = (l + 1) % n;                         // Move to the lower sum side               else                r = (n + r - 1) % n;        }        return false;    }     // Driver Code    public static void Main ()    {        int []arr = {11, 15, 6, 8, 9, 10};        int sum = 16;        int n = arr.Length;             if (pairInSortedRotated(arr, n, sum))            Console.WriteLine("Array has two elements" +                                       " with sum 16");        else        Console.WriteLine("Array doesn't have two" +                            " elements with sum 16 ");    }} // This code is contributed by vt_m.
<?php// PHP program to find a pair// with a given sum in a// sorted and rotated array // This function returns true// if arr[0..n-1] has a pair// with sum equals to x. function pairInSortedRotated($arr, $n, $x){    // Find the pivot element    $i;    for ($i = 0; $i < $n - 1; $i++)        if ($arr[$i] > $arr[$i + 1])            break;             // l is now index of    // smallest element    $l = ($i + 1) % $n;         // r is now index of    // largest element    $r = $i;     // Keep moving either l    // or r till they meet    while ($l != $r)    {        // If we find a pair with        // sum x, we return true        if ($arr[$l] + $arr[$r] == $x)            return true;         // If current pair sum is        // less, move to the higher sum        if ($arr[$l] + $arr[$r] < $x)            $l = ($l + 1) % $n;                     // Move to the lower sum side        else            $r = ($n + $r - 1) % $n;    }    return false;} // Driver Code$arr = array(11, 15, 6, 8, 9, 10);$sum = 16;$n = sizeof($arr); if (pairInSortedRotated($arr, $n, $sum))    echo "Array has two elements ".                     "with sum 16";else    echo "Array doesn't have two ".           "elements with sum 16 "; // This code is contributed by aj_36?>
<script> // Javascript program to find a// pair with a given sum in a// sorted and rotated array     // This function returns true if arr[0..n-1]// has a pair with sum equals to x.function pairInSortedRotated(arr, n, x){         // Find the pivot element    let i;    for(i = 0; i < n - 1; i++)        if (arr[i] > arr[i + 1])            break;                 // l is now index of                                             // smallest element             let l = (i + 1) % n;         // r is now index of largest    // element                      let r = i;              // Keep moving either l or    // r till they meet    while (l != r)    {                  // If we find a pair with sum x, we         // return true         if (arr[l] + arr[r] == x)              return true;             // If current pair sum is less, move         // to the higher sum         if (arr[l] + arr[r] < x)              l = (l + 1) % n;                        // Move to the lower sum side               else               r = (n + r - 1) % n;    }    return false;} // Driver codelet arr = [ 11, 15, 6, 8, 9, 10 ];let sum = 16;let n = arr.length; if (pairInSortedRotated(arr, n, sum))    document.write("Array has two elements" +                   " with sum 16");else    document.write("Array doesn't have two" +                   " elements with sum 16 "); // This code is contributed by avanitrachhadiya2155     </script>
Output : 
Array has two elements with sum 16
Time Complexity: O(n)
The step to find the pivot can be optimized to O(Logn) using the Binary Search approach discussed here.
Auxiliary Space: O(1)
As constant extra space is used.
How to count all pairs having sum x? The stepwise algorithm is:  
Find the pivot element of the sorted and the rotated array. The pivot element is the largest element in the array. The smallest element will be adjacent to it.Use two pointers (say left and right) with the left pointer pointing to the smallest element and the right pointer pointing to largest element.Find the sum of the elements pointed by both the pointers.If the sum is equal to x, then increment the count. If the sum is less than x, then to increase sum move the left pointer to next position by incrementing it in a rotational manner. If the sum is greater than x, then to decrease sum move the right pointer to next position by decrementing it in rotational manner.Repeat step 3 and 4 until the left pointer is not equal to the right pointer or until the left pointer is not equal to right pointer – 1.Print final count.
Find the pivot element of the sorted and the rotated array. The pivot element is the largest element in the array. The smallest element will be adjacent to it.
Use two pointers (say left and right) with the left pointer pointing to the smallest element and the right pointer pointing to largest element.
Find the sum of the elements pointed by both the pointers.
If the sum is equal to x, then increment the count. If the sum is less than x, then to increase sum move the left pointer to next position by incrementing it in a rotational manner. If the sum is greater than x, then to decrease sum move the right pointer to next position by decrementing it in rotational manner.
Repeat step 3 and 4 until the left pointer is not equal to the right pointer or until the left pointer is not equal to right pointer – 1.
Print final count.
Below is implementation of above algorithm: 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find number of pairs with// a given sum in a sorted and rotated array.#include<bits/stdc++.h>using namespace std; // This function returns count of number of pairs// with sum equals to x.int pairsInSortedRotated(int arr[], int n, int x){    // Find the pivot element. Pivot element    // is largest element of array.    int i;    for (i = 0; i < n-1; i++)        if (arr[i] > arr[i+1])            break;         // l is index of smallest element.    int l = (i + 1) % n;         // r is index of largest element.    int r = i;         // Variable to store count of number    // of pairs.    int cnt = 0;     // Find sum of pair formed by arr[l] and    // and arr[r] and update l, r and cnt    // accordingly.    while (l != r)    {        // If we find a pair with sum x, then        // increment cnt, move l and r to        // next element.        if (arr[l] + arr[r] == x){            cnt++;                         // This condition is required to            // be checked, otherwise l and r            // will cross each other and loop            // will never terminate.            if(l == (r - 1 + n) % n){                return cnt;            }                         l = (l + 1) % n;            r = (r - 1 + n) % n;        }         // If current pair sum is less, move to        // the higher sum side.        else if (arr[l] + arr[r] < x)            l = (l + 1) % n;                 // If current pair sum is greater, move        // to the lower sum side.        else            r = (n + r - 1)%n;    }         return cnt;} /* Driver program to test above function */int main(){    int arr[] = {11, 15, 6, 7, 9, 10};    int sum = 16;    int n = sizeof(arr)/sizeof(arr[0]);     cout << pairsInSortedRotated(arr, n, sum);         return 0;}
// Java program to find// number of pairs with// a given sum in a sorted// and rotated array.import java.io.*; class GFG{     // This function returns// count of number of pairs// with sum equals to x.static int pairsInSortedRotated(int arr[],                                int n, int x){    // Find the pivot element.    // Pivot element is largest    // element of array.    int i;    for (i = 0; i < n - 1; i++)        if (arr[i] > arr[i + 1])            break;         // l is index of    // smallest element.    int l = (i + 1) % n;         // r is index of    // largest element.    int r = i;         // Variable to store    // count of number    // of pairs.    int cnt = 0;     // Find sum of pair    // formed by arr[l]    // and arr[r] and    // update l, r and    // cnt accordingly.    while (l != r)    {        // If we find a pair with        // sum x, then increment        // cnt, move l and r to        // next element.        if (arr[l] + arr[r] == x)        {            cnt++;                         // This condition is required            // to be checked, otherwise            // l and r will cross each            // other and loop will never            // terminate.            if(l == (r - 1 + n) % n)            {                return cnt;            }                         l = (l + 1) % n;            r = (r - 1 + n) % n;        }         // If current pair sum        // is less, move to        // the higher sum side.        else if (arr[l] + arr[r] < x)            l = (l + 1) % n;                 // If current pair sum        // is greater, move        // to the lower sum side.        else            r = (n + r - 1) % n;    }         return cnt;} // Driver Codepublic static void main (String[] args){    int arr[] = {11, 15, 6, 7, 9, 10};    int sum = 16;    int n = arr.length;     System.out.println(            pairsInSortedRotated(arr, n, sum));}} // This code is contributed by ajit
# Python program to find# number of pairs with# a given sum in a sorted# and rotated array. # This function returns# count of number of pairs# with sum equals to x.def pairsInSortedRotated(arr, n, x):         # Find the pivot element.    # Pivot element is largest    # element of array.    for i in range(n):        if arr[i] > arr[i + 1]:            break         # l is index of    # smallest element.    l = (i + 1) % n         # r is index of    # largest element.    r = i         # Variable to store    # count of number    # of pairs.    cnt = 0     # Find sum of pair    # formed by arr[l]    # and arr[r] and    # update l, r and    # cnt accordingly.    while (l != r):                 # If we find a pair        # with sum x, then        # increment cnt, move        # l and r to next element.        if arr[l] + arr[r] == x:            cnt += 1                         # This condition is            # required to be checked,            # otherwise l and r will            # cross each other and            # loop will never terminate.            if l == (r - 1 + n) % n:                return cnt                         l = (l + 1) % n            r = (r - 1 + n) % n                 # If current pair sum        # is less, move to        # the higher sum side.        elif arr[l] + arr[r] < x:            l = (l + 1) % n                 # If current pair sum        # is greater, move to        # the lower sum side.        else:            r = (n + r - 1) % n         return cnt # Driver Codearr = [11, 15, 6, 7, 9, 10]s = 16 print(pairsInSortedRotated(arr, 6, s)) # This code is contributed# by ChitraNayal
// C# program to find// number of pairs with// a given sum in a sorted// and rotated array.using System; class GFG{     // This function returns// count of number of pairs// with sum equals to x.static int pairsInSortedRotated(int []arr,                                int n, int x){    // Find the pivot element.    // Pivot element is largest    // element of array.    int i;    for (i = 0; i < n - 1; i++)        if (arr[i] > arr[i + 1])            break;         // l is index of    // smallest element.    int l = (i + 1) % n;         // r is index of    // largest element.    int r = i;         // Variable to store    // count of number    // of pairs.    int cnt = 0;     // Find sum of pair    // formed by arr[l]    // and arr[r] and    // update l, r and    // cnt accordingly.    while (l != r)    {        // If we find a pair with        // sum x, then increment        // cnt, move l and r to        // next element.        if (arr[l] + arr[r] == x)        {            cnt++;                         // This condition is required            // to be checked, otherwise            // l and r will cross each            // other and loop will never            // terminate.            if(l == (r - 1 + n) % n)            {                return cnt;            }                         l = (l + 1) % n;            r = (r - 1 + n) % n;        }         // If current pair sum        // is less, move to        // the higher sum side.        else if (arr[l] + arr[r] < x)            l = (l + 1) % n;                 // If current pair sum        // is greater, move        // to the lower sum side.        else            r = (n + r - 1) % n;    }         return cnt;} // Driver Codestatic public void Main (){    int []arr = {11, 15, 6, 7, 9, 10};    int sum = 16;    int n = arr.Length;         Console.WriteLine(            pairsInSortedRotated(arr, n, sum));}} // This code is contributed by akt_mit
<?php// PHP program to find number// of pairs with a given sum// in a sorted and rotated array. // This function returns count// of number of pairs with sum// equals to x.function pairsInSortedRotated($arr,                              $n, $x){    // Find the pivot element.    // Pivot element is largest    // element of array.    $i;    for ($i = 0; $i < $n - 1; $i++)        if ($arr[$i] > $arr[$i + 1])            break;         // l is index of    // smallest element.    $l = ($i + 1) % $n;         // r is index of    // largest element.    $r = $i;         // Variable to store    // count of number    // of pairs.    $cnt = 0;     // Find sum of pair formed    // by arr[l] and arr[r] and    // update l, r and cnt    // accordingly.    while ($l != $r)    {        // If we find a pair with        // sum x, then increment        // cnt, move l and r to        // next element.        if ($arr[$l] + $arr[$r] == $x)        {            $cnt++;                         // This condition is required            // to be checked, otherwise l            // and r will cross each other            // and loop will never terminate.            if($l == ($r - 1 + $n) % $n)            {                return $cnt;            }                         $l = ($l + 1) % $n;            $r = ($r - 1 + $n) % $n;        }         // If current pair sum        // is less, move to        // the higher sum side.        else if ($arr[$l] + $arr[$r] < $x)            $l = ($l + 1) % $n;                 // If current pair sum        // is greater, move to        // the lower sum side.        else            $r = ($n + $r - 1) % $n;    }         return $cnt;} // Driver Code$arr = array(11, 15, 6,              7, 9, 10);$sum = 16;$n = sizeof($arr) / sizeof($arr[0]); echo pairsInSortedRotated($arr,                              $n, $sum); // This code is contributed by ajit?>
<script>// Javascript program to find// number of pairs with// a given sum in a sorted// and rotated array.         // This function returns    // count of number of pairs    // with sum equals to x.    function pairsInSortedRotated(arr,n,x)    {        // Find the pivot element.        // Pivot element is largest        // element of array.        let i;        for (i = 0; i < n - 1; i++)            if (arr[i] > arr[i + 1])                break;                  // l is index of        // smallest element.        let l = (i + 1) % n;                  // r is index of        // largest element.        let r = i;                  // Variable to store        // count of number        // of pairs.        let cnt = 0;              // Find sum of pair        // formed by arr[l]        // and arr[r] and        // update l, r and        // cnt accordingly.        while (l != r)        {            // If we find a pair with            // sum x, then increment            // cnt, move l and r to            // next element.            if (arr[l] + arr[r] == x)            {                cnt++;                                  // This condition is required                // to be checked, otherwise                // l and r will cross each                // other and loop will never                // terminate.                if(l == (r - 1 + n) % n)                {                    return cnt;                }                                  l = (l + 1) % n;                r = (r - 1 + n) % n;            }                  // If current pair sum            // is less, move to            // the higher sum side.            else if (arr[l] + arr[r] < x)                l = (l + 1) % n;                          // If current pair sum            // is greater, move            // to the lower sum side.            else                r = (n + r - 1) % n;        }                  return cnt;    }         // Driver Code    let arr = [11, 15, 6, 7, 9, 10];    let sum = 16;    let n = arr.length;    document.write(pairsInSortedRotated(arr, n, sum));         //  This code is contributed by rag2127</script>
Output: 
2
Time Complexity: O(n) 
As we are performing linear operations on array.
Auxiliary Space: O(1) 
As constant extra space is used.This method is suggested by Nikhil Jindal. 
Find if there is a pair with a given sum in a sorted and rotated array | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersFind if there is a pair with a given sum in a sorted and rotated array | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=8KuFojXysg0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Exercise: 1) Extend the above solution to work for arrays with duplicates allowed.This article is contributed by Himanshu Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
jit_t
nik1996
ukasp
mukeshmk95
sagarudasi2
Stark17
avanitrachhadiya2155
rag2127
kargiloutlook
abhijeet19403
rotation
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Find the Missing Number
Search, insert and delete in an unsorted array
Program to find largest element in an array
k largest(or smallest) elements in an array
Given an array of size n and a number k, find all elements that appear more than n/k times
Two Pointers Technique
Find the missing and repeating number