Java Program for Given a sorted and rotated array, find if there is a pair with a given sum
Last Updated :
14 Feb, 2023
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.
Java
// Java program to find a pair with a given
// sum in a sorted and rotated array
class 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*/
Output :
Array has two elements with sum 16
The 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 here.
Space complexity: O(1),as we only need a few variables to store intermediate values.
How to count all pairs having sum x?
The stepwise algo 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.
Below is implementation of above algorithm:
Java
// 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 Code
public 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
Output:
2
Time Complexity: O(n)
Auxiliary Space: O(1)
This method is suggested by Nikhil Jindal.
Exercise:
1) Extend the above solution to work for arrays with duplicates allowed.
Please refer complete article on Given a sorted and rotated array, find if there is a pair with a given sum for more details!
Similar Reads
Java Program for Check if an array is sorted and rotated Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 } Output : YES The above ar
3 min read
Java Program for Search an element in a sorted and rotated array An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. Examp
9 min read
Java Program for Maximum sum of i*arr[i] among all rotations of a given array Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1. Examples: Input: arr[] = {8, 3, 1, 2} Output: 29 Explanation: Lets look at all the rotations, {8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11 {3, 1, 2, 8} = 3*0 + 1*1 + 2*2 +
6 min read
Java Program to Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed Given an array, only rotation operation is allowed on array. We can rotate the array as many times as we want. Return the maximum possible summation of i*arr[i]. Examples :Â Â Input: arr[] = {1, 20, 2, 10} Output: 72 We can get 72 by rotating array twice. {2, 10, 1, 20} 20*3 + 1*2 + 10*1 + 2*0 = 72 I
4 min read
Java Program to Find k pairs with smallest sums in two arrays Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[]Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3 Output : [1, 2], [1, 4], [1, 6] E
3 min read
Java Program for Queries to find maximum sum contiguous subarrays of given length in a rotating array Given an array arr[] of N integers and Q queries of the form {X, Y} of the following two types: If X = 1, rotate the given array to the left by Y positions.If X = 2, print the maximum sum subarray of length Y in the current state of the array. Examples:Â Input: N = 5, arr[] = {1, 2, 3, 4, 5}, Q = 2,
5 min read
Java Program for Count pairs with given sum Given an array of integers, and a number 'sum', find the number of pairs of integers in the array whose sum is equal to 'sum'. Examples: Input : arr[] = {1, 5, 7, -1}, sum = 6 Output : 2 Pairs with sum 6 are (1, 5) and (7, -1) Input : arr[] = {1, 5, 7, -1, 5}, sum = 6 Output : 3 Pairs with sum 6 are
4 min read
Java Program to Find Range sum queries for anticlockwise rotations of Array by K indices Given an array arr consisting of N elements and Q queries of the following two types: 1 K: For this type of query, the array needs to be rotated by K indices anticlockwise from its current state.2 L R: For this query, the sum of the array elements present in the indices [L, R] needs to be calculated
4 min read
Java Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided ar
5 min read
Java Program For Finding Subarray With Given Sum - Set 1 (Nonnegative Numbers) Given an unsorted array of nonnegative integers, find a continuous subarray which adds to a given number. Examples : Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33 Output: Sum found between indexes 2 and 4 Sum of elements between indices 2 and 4 is 20 + 3 + 10 = 33 Input: arr[] = {1, 4, 0, 0, 3, 10,
5 min read