C Program for Given a sorted and rotated array, find if there is a pair with a given sum
Last Updated :
20 Oct, 2023
Write a C program for a given array arr[] of distinct elements size N that is sorted and then rotated around an unknown point, the task is to check if the array has a pair with a given sum X.
Examples :
Input: arr[] = {11, 15, 6, 8, 9, 10}, x = 16
Output: true
Explanation: There is a pair (6, 10) with sum 16
Input: arr[] = {11, 15, 26, 38, 9, 10}, x = 35
Output: true
Explanation: There is a pair (26, 9) with sum 35
Input: arr[] = {11, 15, 26, 38, 9, 10}, x = 45
Output: false
Explanation: There is no pair with sum 45.
We have discussed an O(n) solution for a sorted array (See steps 2, 3, and 4 of Method 1) in this article. We can extend this solution for the rotated arrays as well.
Approach:
First find the largest element in an array which is the pivot point also and the element just after the largest is the smallest element. Once we have the indices of the largest and the smallest elements, we use a similar meet-in-middle algorithm (as discussed here in method 1) to find if there is a pair.
The only thing new here is indices are incremented and decremented in a rotational manner using modular arithmetic.
Illustration:
Let us take an example arr[]={11, 15, 6, 8, 9, 10}, sum=16.
pivot = 1,
l = 2, r = 1:
=> arr[2] + arr[1] = 6 + 15 = 21 which is > 16
=> So decrement r circularly. r = ( 6 + 1 – 1) % 6, r = 0
l = 2, r = 0:
=> arr[2] + arr[0] = 17 which is > 16.
=> So decrement r circularly. r = (6 + 0 – 1) % 6, r = 5
l = 2, r = 5:
=> arr[2] + arr[5] = 16 which is equal to 16.
=> Hence return true
Hence there exists such a pair.
Step-by-step approach:
- We will run a for loop from 0 to N-1, to find out the pivot point.
- Set the left pointer(l) to the smallest value and the right pointer(r) to the highest value.
- To restrict the circular movement within the array we will apply the modulo operation by the size of the array.
- While l ! = r, we shall keep checking if arr[l] + arr[r] = sum.
- If arr[l] + arr[r] is greater than X, update r = (N+r-1) % N.
- If arr[l] + arr[r] is less than X, update l = (l+1) % N.
- If arr[l] + arr[r] is equal to the value X, then return true.
- If no such pair is found after the iteration is complete, return false.
Below is the implementation of the above approach:
C
// C code to implement the approach
#include <stdio.h>
// This function returns true if arr[0..n-1]
// has a pair with sum equals to x.
int 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 1;
}
// 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 0;
}
// Driver code
int main()
{
int arr[] = { 11, 15, 6, 8, 9, 10 };
int sum = 16;
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
if (pairInSortedRotated(arr, n, sum)) {
printf("true\n");
}
else {
printf("false\n");
}
return 0;
}
Time Complexity: 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)
C Program for Given a sorted and rotated array, find if there is a pair with a given sum using Two Pointers Technique and Binary Search.
The approach finds the pivot element in the rotated sorted array and then uses two pointers to check if there is a pair with a given sum. The pointers move in a circular way using the modulo operator.
Steps-by-step approach:
- Find the pivot element in the rotated sorted array. If the pivot element is greater than the first element of the array, then the pivot lies in the second half of the array; otherwise, it lies in the first half of the array.
- After finding the pivot element, initialize two pointers left and right at the start and end of the array, respectively.
- Loop through the array and check if the sum of the elements at the left and right pointers is equal to the given sum. If it is, then return true.
- If the sum is less than the given sum, increment the left pointer, else decrement the right pointer.
- If the loop completes and no pair is found, return false.
Below in the implementation of the above approach:
C
// C code to implement the approach
#include <stdio.h>
// Function to find a pair with a given sum in a sorted and
// rotated array
int findPair(int arr[], int n, int x)
{
// Find the pivot element
int pivot = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
pivot = i + 1;
break;
}
}
// Set left and right pointers
int left = pivot;
int right = (pivot - 1 + n) % n;
// Loop until left and right pointers meet
while (left != right) {
// If the sum of elements at left and right pointers
// is equal to x, return 1 (true)
if (arr[left] + arr[right] == x) {
return 1;
}
// If the sum of elements at left and right pointers
// is less than x, move the left pointer to the next
// element
else if (arr[left] + arr[right] < x) {
left = (left + 1) % n;
}
// If the sum of elements at left and right pointers
// is greater than x, move the right pointer to the
// previous element
else {
right = (right - 1 + n) % n;
}
}
// Return 0 (false) if a pair is not found
return 0;
}
// Driver Code
int main()
{
// Initialize array and variables
int arr[] = { 11, 15, 6, 8, 9, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 16;
// Call the function and print the result
if (findPair(arr, n, x)) {
printf("true\n");
}
else {
printf("false\n");
}
return 0;
}
Time Complexity: O(n)
Auxiliary Space: O(1)
Exercise:
Extend the above solution to work for arrays with duplicates allowed.
Please write comments if you find anything incorrect, or you want to
share more information about the topic discussed above
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
C 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. Exam
4 min read
C Program to Find a pair with the given difference
Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78 Output: Pair Found: (2, 80) Input: arr[] = {90, 70, 20, 80, 50}, n = 45 Output: No Such Pair Recommended: Please solve it on "PRA
3 min read
C 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
C Program for Two Pointers Technique
Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Letâs see the naive so
3 min read
Java Program for Given a sorted and rotated array, find if there is a pair with a given sum
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: ar
6 min read
Count of Pairs with given sum in Rotated Sorted Array
Given an array arr[] of distinct elements size N that is sorted and then around an unknown point, the task is to count the number of pairs in the array having a given sum X. Examples: Input: arr[] = {11, 15, 26, 38, 9, 10}, X = 35Output: 1Explanation: There is a pair (26, 9) with sum 35 Input: arr[]
13 min read
Given an absolute sorted array and a number K, find the pair whose sum is K
Given an absolute sorted array arr[] and a number target, the task is to find a pair of elements in the given array that sum to target. If no such pair exist in array the return an empty array.An absolute sorted array is an array of numbers in which |arr[i]| <= |arr[j]|, for all i < j.Examples
15+ min read
C++ Program for 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
7 min read
C++ 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
5 min read
C++ 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. Exam
7 min read