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 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

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Index Pair Structure
struct indexPair {
    int index_1, index_2;
};
  
// Function to find positive and
// Negative pairs
indexPair findPositiveNegativePairs(
    const vector<int>& arr, int k)
{
  
    // result.index_1 for positive number &
    // result.index_2 for negative number
    indexPair result = indexPair{
        static_cast<int>(arr.size() - 1),
        static_cast<int>(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 pairs
template <typename T>
indexPair findPairsOfSameSign(
    const vector<int>& arr, int k, T compare)
{
  
    // Intializing the index pairs with
    // 0 and the end of array length - 1
    indexPair result
        = indexPair{
              0,
              static_cast<int>(arr.size() - 1)
          };
  
    // Loop to find the first positive or negative
    // number in the array according to the given
    // comparision 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
    // comparision 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;
        }
  
        // Conditon if the curent 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 K
indexPair FindPairs(const vector<int>& 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<int>())
                   : findPairsOfSameSign(
                         arr, k, greater_equal<int>());
    }
    return result;
}
  
// Driver Code
int main()
{
    vector<int> 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;
}

chevron_right


Output:

3 7

Time Complexity: O(N)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.