# Given an absolute sorted array and a number K, find the pair whose sum is K

• Difficulty Level : Easy
• Last Updated : 02 Feb, 2023

Given an absolute sorted array arr[] and a number K, the task is to find a pair of elements in the given array that sum to K. An absolute sorted array is an array of numbers in which |arr[i]| â‰¤ |arr[j]| whenever i < j.

Examples:

Input: arr[] = {-49, 75, 103, -147, 164, -197, -238, 314, 348, -422}, K = 167
Output: 3 7
(arr[3] + arr[7]) = (-147 + 314) = 167.

Input: arr[] = {-8, 10, -15, 12, 24}, K = 22
Output: 1 3

Naive Approach:- The simple approach to find a pair is to check for each element in the array for another element. If no pair found then returning -1,-1

Implementation:-

## C++

 // C++ implementation of above approach #include using namespace std; //function to return answerpair FindPair(vector A,int K){      //pair to store answer      pair ans;             //iterating over array      for(int i=0;i A;    A.push_back(-49);    A.push_back(75);    A.push_back(103);    A.push_back(-147);    A.push_back(164);    A.push_back(-197);    A.push_back(-238);    A.push_back(314);    A.push_back(348);    A.push_back(-422);    int K = 167;    pair result = FindPair(A, K);     cout << result.first << ' '         << result.second;     return 0;} //This code contributed by shubhamrajput6156

## Python3

 # Python implementation of above approach # function to return answerdef find_pair(A, K):    for i in range(len(A) - 1):        for j in range(i + 1, len(A)):                         # if found such pair            if A[i] + A[j] == K:                               # returning answer                return (i, j)                   # if no pair exist    return (-1, -1) # driver codeA = []A.append(-49)A.append(75)A.append(103)A.append(-147)A.append(164)A.append(-197)A.append(-238)A.append(314)A.append(348)A.append(-422)K = 167result = find_pair(A, K) print(result) # This code is contributed by redmoonz.

Output:-  3 7

Time Complexity:- O(N^2) where N is size of array

Space Complexity:- O(1)

Efficient Approach: For a sorted array, use the approach discussed in this article. In case of an absolute sorted array, there are generally three cases for pairs according to their property:

1. Both the numbers in the pair are negative.
2. Both the numbers in the pair are positive.
3. One is negative and the other is positive.

For cases (1) and (2), use the Two Pointer Approach separately by just limiting to consider either positive or negative numbers.
For case (3), use the same Two pointer approach where we have one index for positive numbers and one index for negative numbers, and they both start from the highest possible index and then go down.

Below is the implementation of the above approach:

## C++

 // C++ implementation of above approach #include using namespace std; // Index Pair Structurestruct indexPair {    int index_1, index_2;}; // Function to find positive and// Negative pairsindexPair findPositiveNegativePairs(    const vector& arr, int k){     // result.index_1 for positive number &    // result.index_2 for negative number    indexPair result = indexPair{        static_cast(arr.size() - 1),        static_cast(arr.size() - 1)    };     // Find the last positive or zero number    while (result.index_1 >= 0           && arr[result.index_1] < 0) {        --result.index_1;    }     // Find the last negative number    while (result.index_2 >= 0           && arr[result.index_2] >= 0) {        --result.index_2;    }     // Loop to find the pair with    // Desired Sum    while (result.index_1 >= 0           && result.index_2 >= 0) {         // Condition if the current index pair        // have the desired sum        if (arr[result.index_1]                + arr[result.index_2]            == k) {            return result;        }         // Condition if the current index pairs        // sum is greater than desired sum        else if (arr[result.index_1]                     + arr[result.index_2]                 > k) {             // Loop to find the next            // negative element from last            do {                --result.index_1;            } while (result.index_1 >= 0                     && arr[result.index_1] < 0);        }         // Condition if the current index pairs        // sum is less than desired sum        else {             // Loop to find the next            // positive or zero number from last            do {                --result.index_2;            } while (result.index_2 >= 0                     && arr[result.index_2] >= 0);        }    }    return { -1, -1 };} // Function to find positive-positive number// pairs or negative-negative number pairstemplate indexPair findPairsOfSameSign(    const vector& arr, int k, T compare){     // Initializing the index pairs with    // 0 and the end of array length - 1    indexPair result        = indexPair{              0,              static_cast(arr.size() - 1)          };     // Loop to find the first positive or negative    // number in the array according to the given    // comparison template function    while (result.index_1 < result.index_2           && compare(arr[result.index_1], 0)) {        ++result.index_1;    }     // Loop to find the last positive or negative    // number in the array according to the given    // comparison template function    while (result.index_1 < result.index_2           && compare(arr[result.index_2], 0)) {        --result.index_2;    }     // Loop to find the desired pairs    while (result.index_1 < result.index_2) {         // Condition if the current index pair        // have the desired sum        if (arr[result.index_1]                + arr[result.index_2]            == k) {            return result;        }         // Condition if the current index pair        // is greater than or equal to the desired        // sum according to the compare function        else if (compare(arr[result.index_1]                             + arr[result.index_2],                         k)) {             // Loop to find the next positive-positive            // or negative-negative pairs            do {                ++result.index_1;            } while (result.index_1 < result.index_2                     && compare(arr[result.index_1], 0));        }         // Condition if the current index pair is        // greater than or equal to the desired        // sum according to the compare function        else {             // Loop to find the next positive-positive            // or negative-negative pairs            do {                --result.index_2;            } while (result.index_1 < result.index_2                     && compare(arr[result.index_2], 0));        }    }    return { -1, -1 };} // Function to find the pairs whose sum// is equal to the given desired sum KindexPair FindPairs(const vector& arr, int k){    // Find the positive-negative pairs    indexPair result = findPositiveNegativePairs(arr, k);     // Condition to check if positive-negative    // pairs not found in the array    if (result.index_1 == -1        && result.index_2 == -1) {         return k >= 0                   ? findPairsOfSameSign(                         arr, k, less())                   : findPairsOfSameSign(                         arr, k, greater_equal());    }    return result;} // Driver Codeint main(){    vector A;    A.push_back(-49);    A.push_back(75);    A.push_back(103);    A.push_back(-147);    A.push_back(164);    A.push_back(-197);    A.push_back(-238);    A.push_back(314);    A.push_back(348);    A.push_back(-422);    int K = 167;    indexPair result = FindPairs(A, K);     cout << result.index_2 << ' '         << result.index_1;     return 0;}

Output:

3 7

Time Complexity: O(N)

My Personal Notes arrow_drop_up