Open In App
Related Articles

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 

Algorithm:

  1. Create a function FindPair which takes the array A and integer K as input
  2. Create a pair of integers ans to store the indices of the pair which sums to K
  3. Iterate over the array A from index 0 to size-2 (outer loop)
  4. For each iteration of outer loop, iterate over the array A from index i+1 to size-1 (inner loop)
  5. If the sum of A[i] and A[j] is equal to K, store the indices i and j in ans
  6. Return ans
  7. If no pair is found, return {-1,-1}
  8. In the main function, create an array A with the given elements and an integer K with the given value
  9. Call the FindPair function with A and K as input arguments
  10. Print the indices returned by the function.

Implementation:- 

C++

// C++ implementation of above approach
 
#include <bits/stdc++.h>
using namespace std;
 
//function to return answer
pair<int,int> FindPair(vector<int> A,int K)
{
      //pair to store answer
      pair<int,int> ans;
       
      //iterating over array
      for(int i=0;i<A.size()-1;i++)
    {
          for(int j=i+1;j<A.size();j++)
        {
              //if found such pair
              if(A[i]+A[j]==K)
            {
                  ans.first=i;
                  ans.second=j;
                  //returning answer
                  return ans;
            }
        }
    }
       
      //if no pair exist
      return {-1,-1};
}
               
// 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;
    pair<int,int> result = FindPair(A, K);
 
    cout << result.first << ' '
         << result.second;
 
    return 0;
}
 
//This code contributed by shubhamrajput6156

                    

Java

// Java implementation of above approach
import java.util.ArrayList;
import java.util.List;
 
public class Main {
    // Function to return answer
    static int[] FindPair(List<Integer> A, int K)
    {
        // int array to store answer
        int[] ans = new int[2];
 
        // iterating over array
        for (int i = 0; i < A.size() - 1; i++) {
            for (int j = i + 1; j < A.size(); j++) {
                // if found such pair
                if (A.get(i) + A.get(j) == K) {
                    ans[0] = i;
                    ans[1] = j;
                    // returning answer
                    return ans;
                }
            }
        }
 
        // if no pair exist
        return new int[] { -1, -1 };
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        List<Integer> A = new ArrayList<>();
        A.add(-49);
        A.add(75);
        A.add(103);
        A.add(-147);
        A.add(164);
        A.add(-197);
        A.add(-238);
        A.add(314);
        A.add(348);
        A.add(-422);
        int K = 167;
        int[] result = FindPair(A, K);
 
        System.out.println(result[0] + " " + result[1]);
    }
}

                    

Python3

# Python implementation of above approach
 
# function to return answer
def 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 code
A = []
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 = 167
result = find_pair(A, K)
 
print(result)
 
# This code is contributed by redmoonz.

                    

C#

// C# implementation of above approach
using System;
using System.Collections.Generic;
 
namespace ConsoleApp
{
  class Program
  {
    // Function to return answer
    static int[] FindPair(List<int> A, int K)
    {
      // int array to store answer
      int[] ans = new int[2];
 
      // iterating over array
      for (int i = 0; i < A.Count - 1; i++)
      {
        for (int j = i + 1; j < A.Count; j++)
        {
          // if found such pair
          if (A[i] + A[j] == K)
          {
            ans[0] = i;
            ans[1] = j;
            // returning answer
            return ans;
          }
        }
      }
 
      // if no pair exist
      return new int[] { -1, -1 };
    }
 
    // Driver Code
    static void Main(string[] args)
    {
      List<int> A = new List<int>() { -49, 75, 103, -147, 164, -197, -238, 314, 348, -422 };
      int K = 167;
      int[] result = FindPair(A, K);
 
      Console.WriteLine(result[0] + " " + result[1]);
      Console.ReadLine();
    }
  }
}
 
// This code is contributed by vinayetbi1.

                    

Javascript

<script>
 
// javascript implementation of above approach
 
//function to print answer
function FindPair(A , K){
 
    //iterating over array
      for(let i=0;i<A.length -1;i++)
    {
          for(let j=i+1;j<A.length;j++)
        {
              //if found such pair
              if(A[i]+A[j]==K)
            {
                  console.log(i);
                  console.log(j);
                  //returning answer
                  return;
            }
        }
    }
     
    console.log(-1);
     console.log(-1);
      //if no pair exist
      return;
}
     
    // Driver Code
    var A= new Array();
    A.push(-49);
    A.push(75);
    A.push(103);
    A.push(-147);
    A.push(164);
    A.push(-197);
    A.push(-238);
    A.push(314);
    A.push(348);
    A.push(-422);
 
    let K = 167;
     
    // calling function
    FindPair(A, K);
 
   </script>

                    

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 <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)
{
 
    // Initializing 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
    // 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 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;
}

                    

Java

// Java implementation of above approach
import java.util.*;
 
// Index Pair Structure
class IndexPair {
    int index_1, index_2;
}
 
class GFG {
     
    // Function to find positive and
    // Negative pairs
    static IndexPair findPositiveNegativePairs(
        final List<Integer> arr, final int k)
    {
         
        // result.index_1 for positive number &
        // result.index_2 for negative number
        final IndexPair result = new IndexPair();
        result.index_1 = arr.size() - 1;
        result.index_2 = arr.size() - 1;
         
        // Find the last positive or zero number
        while (result.index_1 >= 0
               && arr.get(result.index_1) < 0) {
            --result.index_1;
        }
         
        // Find the last negative number
        while (result.index_2 >= 0
               && arr.get(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.get(result.index_1)
                    + arr.get(result.index_2)
                == k) {
                return result;
            }
             
        // Condition if the current index pairs
         // sum is greater than desired sum
            else if (arr.get(result.index_1)
                         + arr.get(result.index_2)
                     > k) {
                 
            // Loop to find the next
            // negative element from last
                do {
                    --result.index_1;
                } while (result.index_1 >= 0
                         && arr.get(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.get(result.index_2) >= 0);
            }
        }
        return new IndexPair();
    }
     
     
// Function to find positive-positive number
// pairs or negative-negative number pairs
    static IndexPair findPairsOfSameSign(
        final List<Integer> arr, final int k)
    {
     
     
    // Initializing the index pairs with
    // 0 and the end of array length - 1
        final IndexPair result = new IndexPair();
        result.index_1 = 0;
        result.index_2 = 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
               && arr.get(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
               && arr.get(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.get(result.index_1)
                    + arr.get(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 (arr.get(result.index_1)
                         + arr.get(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
                         && arr.get(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
                         && arr.get(result.index_2) >= 0);
            }
        }
        return new IndexPair();
    }
     
    // Function to find the pairs whose sum
    // is equal to the given desired sum K
    static IndexPair FindPairs(final List<Integer> arr, final int k)
    {
         
        // Find the positive-negative pairs
        final 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)
                       : findPairsOfSameSign(
                             arr, k);
        }
        return result;
    }
     
    // Driver Code
    public static void main(String[] args) {
        List<Integer> A = new ArrayList<>();
        A.add(-49);
        A.add(75);
        A.add(103);
        A.add(-147);
        A.add(164);
        A.add(-197);
        A.add(-238);
        A.add(314);
        A.add(348);
        A.add(-422);
        int K = 167;
        IndexPair result = FindPairs(A, K);
        System.out.println(result.index_2 + " " + result.index_1);
    }
 
}
 
//this code is contributed by bhardwajji

                    

Python3

def find_pairs_with_sum(arr, k):
    seen = {}  # Dictionary to store elements seen so far and their indices
 
    for i, num in enumerate(arr):
        complement = k - num  # Calculate the complement needed to reach the target sum
 
        # Check if the complement is in the dictionary (i.e., we've seen it before)
        if complement in seen:
            return [seen[complement], i]
 
        # Store the current number in the dictionary with its index
        seen[num] = i
 
    return None  # No pair with the desired sum found
 
# Driver Code
if __name__ == "__main__":
    A = [-49, 75, 103, -147, 164, -197, -238, 314, 348, -422]
    K = 167
    result = find_pairs_with_sum(A, K)
 
    if result:
        print(result[0], result[1])
    else:
        print("No pair found with the desired sum")

                    

C#

using System;
using System.Collections.Generic;
 
class MainClass
{
    // Function to find pairs in the array with the desired sum
    static int[] FindPairsWithSum(int[] arr, int k)
    {
        Dictionary<int, int> seen = new Dictionary<int, int>();
 
        for (int i = 0; i < arr.Length; i++)
        {
            int num = arr[i];
            int complement = k - num;
 
            // Check if the complement is in the dictionary (i.e., we've seen it before)
            if (seen.ContainsKey(complement))
            {
                return new int[] { seen[complement], i };
            }
 
            // Store the current number in the dictionary with its index
            seen[num] = i;
        }
 
        return null; // No pair with the desired sum found
    }
 
    public static void Main(string[] args)
    {
        int[] A = { -49, 75, 103, -147, 164, -197, -238, 314, 348, -422 };
        int K = 167;
        int[] result = FindPairsWithSum(A, K);
 
        if (result != null)
        {
            Console.WriteLine(result[0] + " " + result[1]);
        }
        else
        {
            Console.WriteLine("No pair found with the desired sum");
        }
    }
}

                    

Javascript

function findPairsWithSum(arr, k) {
  const seen = new Map(); // Map to store elements seen so far and their indices
 
  for (let i = 0; i < arr.length; i++) {
    const num = arr[i];
    const complement = k - num; // Calculate the complement needed to reach the target sum
 
    // Check if the complement is in the Map (i.e., we've seen it before)
    if (seen.has(complement)) {
      return [seen.get(complement), i];
    }
 
    // Store the current number in the Map with its index
    seen.set(num, i);
  }
 
  return null; // No pair with the desired sum found
}
 
// Driver Code
const A = [-49, 75, 103, -147, 164, -197, -238, 314, 348, -422];
const K = 167;
const result = findPairsWithSum(A, K);
 
if (result) {
  console.log(result[0], result[1]);
} else {
  console.log("No pair found with the desired sum");
}
 
// This code is contributed by Dwaipayan Bandyopadhyay

                    

Output
3 7




Time Complexity: O(N)
 



Last Updated : 11 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads