Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Find Pair Sum in Rotated and Sorted array

Easy
0/40
Average time to solve is 10m
profile
Contributed by
21 upvotes
Asked in companies
AmazonAmdocs

Problem statement

Alice and Bob always loved to play with arrays. Alice took a sorted array and rotated it clockwise for a certain number of times.

For example:
Alice took a sorted array = [4,6,8,10,11] and if she rotates it by 3, then the array becomes: [8, 10, 11, 4, 6]. 

After rotating a sorted array, Alice gave a number ‘K’ to Bob and asked him to search for a pair in an array whose sum is equal to K. Since Bob was busy preparing for his semester exams, he asked you to help him.

You are given an array of integers ARR and a number K. Your task is to find out whether there exists a pair in the array ARR with sum K or not. If there exists a pair then you can return TRUE else return FALSE;

Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains a single integer T, representing the number of test cases
Then the T test cases follow.

The first line of each test case contains a number N denoting the size of the array and an integer K representing the sum of pair.

The second line contains N space-separated distinct integers a1, a2, ..., aN — the array elements.

Output format:

For each test case print “YES” if Bob finds the pair else print “NO”.

The output of every test case will be printed in a separate line. 
Note:
You don’t have to print anything, it has already been taken care of. Just implement the given function.
Follow Up:
Can you do this in O(N) time, and without using any extra space?

Constraints

1<= T <=100
2 <= N <= 10000
-10^8 <= A[i] <= 10^8
-10^8 <= k <= 10^8

Time limit: 1 second

Sample Input 1:

3
5 4
5 7 9 1 3
4 2
8 10 11 1
6 -7
-3 3 6 -5 -4 1

Sample Output 1

YES
NO
YES

Explanation For Sample Output 1:

For the first array [5,7,9,1,3] there exists a pair (1,3) whose sum is equal to 4.

For the second array, there exists no pair whose sum is equal to 2.

For the third array, there exists a pair (-3,-4) whose sum is equal to -7.

Sample Input 2:

3
6 -10
3 4 5 6 1 2
2 0
10 -10
4 -20
5 6 7 1

Sample Output 2:

NO
YES
NO
Hint

Think about finding the sum of all possible pairs

Approaches (3)
Brute force

We will find all the possible pairs by iterating over the whole array N times. At any time if the sum of any pair is equal to K we will return TRUE else keep on iterating.

 

  • Let’s say we have a given array ARR and pair sum K.
  • Iterate over ARR[i] for each i from 0 to N and do:
    • Iterate over ARR[j] for each j from i+1 to N and do:
      • Check if  ARR[i] + Arr[j] is equal to K then return TRUE
  • Return FALSE.
Time Complexity

O(N ^ 2) where N is the length of the string.

 

Since for each element we are iterating over the whole array. So for N element iterating N times, hence the time complexity is O(N ^ 2)

Space Complexity

O(1).

 

Since we are using constant extra space.

Code Solution
(100% EXP penalty)
Find Pair Sum in Rotated and Sorted array
All tags
Sort by
Search icon

Interview problems

Binary Search || Two Pointers | C++ Sol

#include <bits/stdc++.h>

bool findPairSum(vector<int> arr, int target) {
    int n = arr.size();
    int low = 0;
    int high = n - 1;
    int pivot = 0;

    while (low <= high) {
        int mid = (high - low) / 2 + low;

        if (arr[mid + 1] < arr[mid]) {
            pivot = mid + 1;
            break;
        }

        if (arr[mid - 1] > arr[mid]) {
            pivot = mid;
            break;
        }

        if (arr[high] < arr[mid]) {
            low = mid + 1;
        } 
        else {
            high = mid - 1;
        }
    }

    int st = pivot;
    int end = (n + pivot - 1) % n;

    while (st != end) {
        int temp = arr[st] + arr[end];

        if (temp == target) {
            return true;
        } 
        else if (temp < target) {
            st = (st + 1) % n;
        } 
        else {
            end = (n + end - 1) % n;
        }
    }
    return false;
}

programming

datastructures

9 views
0 replies
0 upvotes

Interview problems

Best Solution in Java with Explanation

As it is rotated sorted array so i just made it unrotated sorted array that means i just sort the whole array by using inbuilt sorting system in Java. If you want you can do this sorting by using mergeSort or further better algorithm.  

Then I create two pointer start and end which indicate the first position and last position of the array and i compare the sum of this two pointer with the targetted value.  If targetted value is small then decrement the end by one else increment the start by one.  If targetted value is equal to it's sum then return true. else the loop will iterate until start is greater than or equal to end.  if it not return inside the loop it will return false as it came outside from that loop

 

The overall time complexity of the code is O(n log n) due to the sorting operation.

 

As for space complexity, the code uses only a constant amount of extra space for variables like start, end, and sum, regardless of the size of the input array. So, the space complexity is O(1), indicating constant space usage. Please upvote me.


import java.util.*;

public class Solution {

    public static boolean findPairSum(int[] arr, int target) {
        Arrays.sort(arr);
        int start = 0;
        int end = arr.length - 1;

        while (start < end) {
            int sum = arr[start] + arr[end];
            if (sum == target) {
                return true;
            } else if (sum < target) {
                start++;
            } else {
                end--;
            }
        }
        return false;
    }
}
46 views
0 replies
1 upvote

Interview problems

Python easy solution

def findPairSum(arr, target):
    dict={}
    for i,num in enumerate (arr):
        want=target-arr[i]
        if want in dict:
            return True
        
        dict[num]=1


    return False
41 views
0 replies
0 upvotes

Interview problems

c++ easy sol

sort(arr.begin(),arr.end());

int n=arr.size();

int s=0;

int e=n-1;

while(s<e){

if(arr[s]+arr[e]==target){

return true;

}

else if(arr[s]+arr[e]<target){

s++;

}

else{

e--;

}

}

return false;

115 views
0 replies
0 upvotes

Interview problems

Simple Solution

#include <bits/stdc++.h>
using namespace std;

int findPairSum(vector<int> &arr, int target) {
  sort(arr.begin(), arr.end());
  unordered_map<int, int> mp;

  for (auto num : arr) {
    if (mp.count(target - num))
      return true;

    mp[num]++;
  }

  return false;
}
111 views
0 replies
0 upvotes

Interview problems

Find if there is a pair with a given sum in the rotated sorted Array

Optimized java solution:-

import java.util.* ;

import java.io.*; 

public class Solution 

{

    public static boolean findPairSum(int[] a, int sum) 

    {

        int n=a.length;

        int s=pivot(a);

        int e=(s-1+n)%n;

        while(s!=e){

            

            if((a[s]+a[e])==sum){

                return true;

            }else if((a[s]+a[e])<sum){

                s=(s+1)%n;

            }else{

                e=(e-1+n)%n;

            }

        }

        return false;

    }

    public static int pivot(int a[]){

        int s=0,e=a.length-1;

        if(a.length==1) return 0;

        if(a[s]<a[e]) return 0;

        while(s<=e){

            int m=s+(e-s)/2;

            if(a[m]>a[m+1]) return m+1;

            if(a[m-1]>a[m]) return m;

 

            if(a[s]<a[m]) {

                s=m+1;

            }else{

                e=m-1;

            }

        }

        return -1;

    }

}

datastructures

java

157 views
0 replies
0 upvotes

Interview problems

java solution

// Write your code here

        for(int i = 0;i<arr.length;i++){

            for(int j = i+1;j<arr.length;j++){

                if((arr[i]+arr[j])==target)return true;

            }

        }

        return false;

107 views
0 replies
0 upvotes

Interview problems

Python Sol

def findPairSum(arr, target):
    #Write your code here
    n=len(arr)
    i=0
    while i<n-1:
        if arr[i]>arr[i+1]:
            break
        i+=1
    l=(i+1)%n
    r=i
    while(l!=r):
        if arr[l]+arr[r]==target:
            return True
        elif arr[l]+arr[r]>target:
            r=(n+r-1)%n
        else:
            l=(l+1)%n
    return False

python

110 views
0 replies
0 upvotes

Interview problems

O(N) solution with cpp rotate() and comments

int findPairSum(vector<int> a, int x){
    int k=-1; //rotate point
    int n = a.size();
    //finding the rotate point
    for(int i=0; i<n-1; ++i){
        if(a[i+1]<a[i]) {
            k=i;
            break;
        }
    };
    //rotating to sort the array if not already sorted
    if(k != -1) rotate(a.begin(), a.begin()+k+1, a.end());

    //finally searching in sorted array
    int i=0, j=n-1;
    // sort(a.begin(), a.end());
    while(i<j){
        if(a[i]+a[j]==x) return 1;
        else if(a[i]+a[j]>x) --j;
        else ++i;
    }
    return 0;
}
319 views
0 replies
1 upvote

Interview problems

c++ sln

int findPairSum(vector<int> arr, int target)

{

    //Write your code here

    int n=arr.size();

    int i;

    for(i=0;i<arr.size();i++)

        if(arr[i]>arr[i+1])

            break;

    int l=(i+1)%n;

    int r=i;

    while(l!=r){

        if(arr[l]+arr[r]==target)

            return true;

        if (arr[l] + arr[r] < target)

            l = (l + 1) % n;

        else

            r = (n + r - 1) % n;

    }

    return false;

    

}

307 views
0 replies
0 upvotes
Full screen
Console