Open In App

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

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

Input: arr[] = [-8, 10, 12, -15, 15, 24], target =  0
Output: [-15, 15]
Explanation: The sum of elements at index 3 and 4 i.e., -15 and 15 is equal to target.

Input: arr[] = [-8, 10, 12, -15, 15, 24], target =  -23
Output: [-8, -15]
Explanation: The sum of elements at index 0 and 3 i.e., -8 and -15 is equal to target.

Input: arr[] = [-8, 10, 12, -15, 15, 24], target =  20
Output: [ ]
Explanation: No pair exist whose sum is equal to target.

[Naive Approach] Using Nested Loop – O(n ^ 2) Time and O(1) Space

The simple approach is to check all possible pairs and identify the pair that adds up to the target. We can use nested loop, where the outer loop selects the first element and the inner loop selects the second element.

C++
// C++ program to find the pair which add up to target 
// in absolute sorted array using nested loop

#include <iostream>
#include <vector>
using namespace std;

vector<int> findPair(vector<int> &arr, int target) {
    vector<int> res;

    // Outer loop will select first element and 
  	// inner loop will select second element of pair
    for (int i = 0; i < arr.size() - 1; i++) {
        for (int j = i + 1; j < arr.size(); j++) {

            // if found such pair
            if (arr[i] + arr[j] == target) {
                res.push_back(arr[i]);
                res.push_back(arr[j]);
                return res;
            }
        }
    }

    // if no pair exist
    return res;
}

int main() {
    vector<int> arr = {-8, 10, 12, -15, 15, 24};
    int target = 0;
    vector<int> res = findPair(arr, target);

    for (int ele : res)
        cout << ele << " ";
    return 0;
}
C
// C program to find the pair which add up to target 
// in absolute sorted array using nested loop

#include <stdio.h>

int* findPair(int arr[], int n, int target, int *resSize) {
    int* res = (int*) malloc(2 * sizeof(int));

    // Outer loop will select first element and 
    // inner loop will select second element of pair
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {

            // if found such pair return it
            if (arr[i] + arr[j] == target) {
                res[0] = arr[i];
                res[1] = arr[j];
              	*resSize = 2;
                return res;
            }
        }
    }

    return res;
}

int main() {
    int arr[] = {-8, 10, -15, 15, 12, 24};
    int target = 0;
    int n = sizeof(arr) / sizeof(arr[0]);
  	int resSize = 0;
    int* res = findPair(arr, n, target, &resSize);
  	
  	for (int i = 0; i < resSize; ++i) 
      	printf("%d ", res[i]);
    return 0;
}
Java
// Java program to find the pair which add up to target 
// in absolute sorted array using nested loop

import java.util.*;

class GfG {

    static ArrayList<Integer> findPair(int[] arr, int target) {
        ArrayList<Integer> res = new ArrayList<>();

        // Outer loop will select first element and 
        // inner loop will select second element of pair
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {

                // if found such pair
                if (arr[i] + arr[j] == target) {
                    res.add(arr[i]);
                    res.add(arr[j]);
                    return res;
                }
            }
        }

        // if no pair exist
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {-8, 10, -15, 15, 12, 24};
        int target = 0;
        ArrayList<Integer> res = findPair(arr, target);

        for (int ele : res)
            System.out.print(ele + " ");
    }
}
Python
# Python program to find the pair which add up to target 
# in absolute sorted array using nested loop

def findPair(arr, target):
    res = []

    # Outer loop will select first element and 
    # inner loop will select second element of pair
    for i in range(len(arr) - 1):
        for j in range(i + 1, len(arr)):

            # if found such pair
            if arr[i] + arr[j] == target:
                res.append(arr[i])
                res.append(arr[j])
                return res

    # if no pair exist
    return res

if __name__ == "__main__":
    arr = [-8, 10, -15, 15, 12, 24]
    target = 0
    res = findPair(arr, target)

    for ele in res:
        print(ele, end=" ")
C#
// C# program to find the pair which add up to target 
// in absolute sorted array using nested loop

using System;
using System.Collections.Generic;

class GfG {
    static List<int> findPair(int[] arr, int target) {
        List<int> res = new List<int>();

        // Outer loop will select first element and 
        // inner loop will select second element of pair
        for (int i = 0; i < arr.Length - 1; i++) {
            for (int j = i + 1; j < arr.Length; j++) {

                // if found such pair
                if (arr[i] + arr[j] == target) {
                    res.Add(arr[i]);
                    res.Add(arr[j]);
                    return res;
                }
            }
        }

        // if no pair exist
        return res;
    }

    static void Main() {
        int[] arr = { -8, 10, -15, 15, 12, 24 };
        int target = 0;
        List<int> res = findPair(arr, target);

        foreach (int ele in res)
            Console.Write(ele + " ");
    }
}
JavaScript
// JavaScript program to find the pair which add up to target 
// in absolute sorted array using nested loop

function findPair(arr, target) {
    let res = [];

    // Outer loop will select first element and 
    // inner loop will select second element of pair
    for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {

            // if found such pair
            if (arr[i] + arr[j] === target) {
                res.push(arr[i], arr[j]);
                return res;
            }
        }
    }

    // if no pair exist
    return res;
}

// driver code
const arr = [-8, 10, -15, 15, 12, 24];
const target = 0;
const res = findPair(arr, target);

console.log(res.join(" "));

Output
-15 15 

[Better Approach] Using Hash Set – O(n) Time and O(n) Space

The idea is that for every element x in the array arr[], we can check if its complement (target – x), exists in the array. To make this search faster, we can use a hash set.

C++
// C++ program to find the pair which add up to target 
// in absolute sorted array using hash set

#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

vector<int> findPair(vector<int> &arr, int target) {
    vector<int> res;

    unordered_set<int> st;
  	for (int ele: arr) {
      	
      	// calculate and search for complement of ele 
      	// in already covered part of array
      	int complement = target - ele;
      	if (st.find(complement) != st.end()) {
          	res.push_back(complement);
          	res.push_back(ele);
          	return res;
        }
      	
      	// if complement is not found then store this element in hash set
      	st.insert(ele);
    }

    // if no pair exist
    return res;
}

int main() {
    vector<int> arr = {-8, 10, 12, -15, 15, 24};
    int target = 0;
    vector<int> res = findPair(arr, target);

    for (int ele : res)
        cout << ele << " ";
    return 0;
}
Java
// Java program to find the pair which adds up to target
// in absolute sorted array using hash set
import java.util.ArrayList;
import java.util.HashSet;

class GfG {
    static ArrayList<Integer> findPair(int[] arr, int target) {
        ArrayList<Integer> res = new ArrayList<>();
        HashSet<Integer> st = new HashSet<>();

        for (int ele : arr) {
          
            // Calculate and search for complement of ele
            // in already covered part of the array
            int complement = target - ele;
            if (st.contains(complement)) {
                res.add(complement);
                res.add(ele);
                return res;
            }
          
            // If complement is not found then store this element in hash set
            st.add(ele);
        }
      
        // If no pair exists
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {-8, 10, 12, -15, 15, 24};
        int target = 0;
        ArrayList<Integer> res = findPair(arr, target);

        for (int ele : res) {
            System.out.print(ele + " ");
        }
    }
}
Python
# Function to find the pair which adds up to target
# in absolute sorted array using hash set
def findPair(arr, target):
    res = []
    st = set()

    for ele in arr:
      
        # Calculate and search for complement of ele
        # in already covered part of array
        complement = target - ele
        if complement in st:
            res.append(complement)
            res.append(ele)
            return res
          
        # If complement is not found then store this element in hash set
        st.add(ele)

    # If no pair exist
    return res
  
if __name__ == "__main__":
    arr = [-8, 10, 12, -15, 15, 24]
    target = 0
    res = findPair(arr, target)

    for ele in res:
        print(ele, end=" ")
C#
// C# program to find the pair which adds up to target
// in absolute sorted array using hash set
using System;
using System.Collections.Generic;

class GfG {
    
    static List<int> findPair(int[] arr, int target) {
        List<int> res = new List<int>();
        HashSet<int> st = new HashSet<int>();

        foreach (int ele in arr) {
          
            // Calculate and search for complement of ele
            // in already covered part of array
            int complement = target - ele;
            if (st.Contains(complement)) {
                res.Add(complement);
                res.Add(ele);
                return res;
            }
          
            // If complement is not found then store this element in hash set
            st.Add(ele);
        }
      
        // If no pair exist
        return res;
    }

    static void Main() {
        int[] arr = {-8, 10, 12, -15, 15, 24};
        int target = 0;
        List<int> res = findPair(arr, target);

        foreach (int ele in res) {
            Console.Write(ele + " ");
        }
    }
}
JavaScript
// Function to find the pair which adds up to target
// in absolute sorted array using hash set
function findPair(arr, target) {
    const res = [];
    const st = new Set();

    for (let ele of arr) {
    
        // Calculate and search for complement of ele
        // in already covered part of array
        const complement = target - ele;
        if (st.has(complement)) {
            res.push(complement);
            res.push(ele);
            return res;
        }
        
        // If complement is not found then store this element in hash set
        st.add(ele);
    }
    
    // If no pair exists
    return res;
}

// driver code
const arr = [-8, 10, 12, -15, 15, 24];
const target = 0;
const res = findPair(arr, target);

console.log(res.join(" "));

Output
-15 15 

[Expected Approach] Using Two Pointers – O(n) Time and O(1) Space

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 number 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 leftmost possible index and then move towards right, skipping there respective opposite numbers.

Note: In absolute sorted array, the negative numbers were arranged in descending order.

Case 1: Both the numbers in the pair are positive, initialize i = 0, j = size – 1.

  • Skip if either arr[i] or arr[j] is negative.
  • If arr[i] + arr[j] < target, to increase the sum, increment i.
  • If arr[i] + arr[j] > target, to decrease the sum, decrement j.
  • If arr[i] + arr[j] == target, pair found.

Case 2: Both the numbers in the pair are negative, initialize i = 0, j = size – 1.

  • Skip if either arr[i] or arr[j] is positive.
  • If arr[i] + arr[j] < target, to increase the sum, decrement j.
  • If arr[i] + arr[j] > target, to decrease the sum increment i.
  • If arr[i] + arr[j] == target, pair found.

Case 3: One number is negative and the other is positive., initialize i = 0, j = 0.

  • Skip if arr[i] is negative or arr[j] is positive.
  • If arr[i] + arr[j] < target, to increase the sum, increment i.
  • If arr[i] + arr[j] > target, to decrease the sum, increment j.
  • If arr[i] + arr[j] == target, pair found.
C++
// C++ program to find the pair which add up to target 
// in absolute sorted array using two pointers

#include <iostream>
#include <vector>
using namespace std;

vector<int> findPair(vector<int> &arr, int target) {
    vector<int> res;

    int i = 0, j = arr.size() - 1;
  	
  	// Case 1: both elements in pair are positive
  	for (int i = 0, j = arr.size() - 1; i < j ; ) {
      	
      	// skip negative elements 
      	if (arr[i] < 0 ) {
          	i++;
        } else if (arr[j] < 0) {
          	j--;
        } 
      	
      	// if both elements are positive check further 
      	else {
          	int sum = arr[i] + arr[j];
          	if(sum == target){
              	res.push_back(arr[i]);
              	res.push_back(arr[j]);
              	return res;
            } 
          	
          	// if sum is smaller, move to larger value
          	else if (sum < target) {  
              	i++;
            } 
          	
          	// if sum is larger, move toward smaller value
          	else {
              	j--;
            } 	 
        }
    }
  	
  	// Case 2: both elements in pair are negative
  	for (int i = 0, j = arr.size() - 1; i < j ; ) {
      	
      	// skip positive elements 
      	if (arr[i] > 0 ) {
          	i++;
        } else if (arr[j] > 0) {
          	j--;
        } 
      	
      	// if both elements are negative check further 
      	else {
          	int sum = arr[i] + arr[j];
          	if(sum == target){
              	res.push_back(arr[i]);
              	res.push_back(arr[j]);
              	return res;
            } 
          	
          	// if sum is smaller, move to larger value
          	else if (sum < target) {  
              	j--;
            } 
          	
          	// if sum is larger, move toward smaller value
          	else {
              	i++;
            } 	 
        }
    }
  	
  	// Case 3: one element in pair is positive and other is negative
    // i point to positive and j point to negative
  	for (int i = 0, j = 0; i < arr.size() && j < arr.size() ; ) {
      
      	// skip negative elements in arr[i] and skip positive in arr[j]
      	if (arr[i] < 0 ) {
          	i++;
        } else if (arr[j] > 0) {
          	j++;
        } 
      
      	// if arr[i] is positive and arr[j] is negative, check further
      	else {
          	int sum = arr[i] + arr[j];
          	if(sum == target){
              	res.push_back(arr[min(i, j)]);
              	res.push_back(arr[max(i, j)]);
              	return res;
            } 
          	
          	// if sum is smaller, move to larger value
          	else if (sum < target) {  
              	i++;
            } 
          	
          	// if sum is larger, move toward smaller value
          	else {
              	j++;
            } 	 
        }
    } 
  
  	return res;
}

int main() {
    vector<int> arr = {-8, 10, 12, -15, 15, 24};
    int target = 0;
    vector<int> res = findPair(arr, target);

    for (int ele : res)
        cout << ele << " ";
    return 0;
}
C
// C program to find the pair which add up to target 
// in absolute sorted array using two pointers

#include <stdio.h>

int* findPair(int arr[], int n, int target, int* resSize) {
    int* res = (int*) malloc(2 * sizeof(int));
	
    // Case 1: both elements in pair are positive
    for (int i = 0, j = n - 1; i < j;) {
      
        // skip negative elements 
        if (arr[i] < 0) {
            i++;
        } else if (arr[j] < 0) {
            j--;
        }
      
        // if both elements are positive check further 
        else {
            int sum = arr[i] + arr[j];
            if (sum == target) {
                res[0] = arr[i];
                res[1] = arr[j];
                return res;
            }
          
            // if sum is smaller, move to larger value
            else if (sum < target) {
                i++;
            }
          
            // if sum is larger, move toward smaller value
            else {
                j--;
            }
        }
    }

    // Case 2: both elements in pair are negative
    for (int i = 0, j = n - 1; i < j;) {
      
        // skip positive elements 
        if (arr[i] > 0) {
            i++;
        } else if (arr[j] > 0) {
            j--;
        }
      
        // if both elements are negative check further 
        else {
            int sum = arr[i] + arr[j];
            if (sum == target) {
                res[0] = arr[i];
                res[1] = arr[j];
                return res;
            }
          
            // if sum is smaller, move to larger value
            else if (sum < target) {
                j--;
            }
          
            // if sum is larger, move toward smaller value
            else {
                i++;
            }
        }
    }

    // Case 3: one element in pair is positive and other is negative
    // i point to positive and j point to negative
    for (int i = 0, j = 0; i < n && j < n;) {
      
        // skip negative elements in arr[i] and skip positive in arr[j]
        if (arr[i] < 0) {
            i++;
        } else if (arr[j] > 0) {
            j++;
        }
      
        // if arr[i] is positive and arr[j] is negative, check further
        else {
            int sum = arr[i] + arr[j];
            if (sum == target) {
                res[0] = arr[i < j ? i : j];
                res[1] = arr[i > j ? i : j];
                return res;
            }
          
            // if sum is smaller, move to larger value
            else if (sum < target) {
                i++;
            }
          
            // if sum is larger, move toward smaller value
            else {
                j++;
            }
        }
    }

    // if no pair found
  	*resSize = 0;
    return res;
}

int main() {
    int arr[] = {-8, 10, 12, -15, 15, 24};
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 0;
  	int resSize = 2;
  
    int* res = findPair(arr, n, target, &resSize);
  	
  	for (int i=0; i < resSize; i++) 
      	printf("%d ", res[i]);
    return 0;
}
Java
// Java program to find the pair which add up to target 
// in absolute sorted array using two pointers

import java.util.ArrayList;

class GfG {

    static ArrayList<Integer> findPair(int[] arr, int target) {
        ArrayList<Integer> res = new ArrayList<>();

        // Case 1: both elements in pair are positive
        for (int i = 0, j = arr.length - 1; i < j;) {
          
            // skip negative elements 
            if (arr[i] < 0) {
                i++;
            } else if (arr[j] < 0) {
                j--;
            } 
          
            // if both elements are positive check further 
            else {
                int sum = arr[i] + arr[j];
                if (sum == target) {
                    res.add(arr[i]);
                    res.add(arr[j]);
                    return res;
                } 
              
                // if sum is smaller, move to larger value
                else if (sum < target) {
                    i++;
                } 
              
                // if sum is larger, move toward smaller value
                else {
                    j--;
                }
            }
        }

        // Case 2: both elements in pair are negative
        for (int i = 0, j = arr.length - 1; i < j;) {
          
            // skip positive elements 
            if (arr[i] > 0) {
                i++;
            } else if (arr[j] > 0) {
                j--;
            } 
          
            // if both elements are negative check further 
            else {
                int sum = arr[i] + arr[j];
                if (sum == target) {
                    res.add(arr[i]);
                    res.add(arr[j]);
                    return res;
                } 
              
                // if sum is smaller, move to larger value
                else if (sum < target) {
                    j--;
                } 
              
                // if sum is larger, move toward smaller value
                else {
                    i++;
                }
            }
        }

        // Case 3: one element in pair is positive and other is negative
        // i point to positive and j point to negative
        for (int i = 0, j = 0; i < arr.length && j < arr.length;) {
          
            // skip negative elements in arr[i] and skip positive in arr[j]
            if (arr[i] < 0) {
                i++;
            } else if (arr[j] > 0) {
                j++;
            } 
          
            // if arr[i] is positive and arr[j] is negative, check further
            else {
                int sum = arr[i] + arr[j];
                if (sum == target) {
                    res.add(arr[Math.min(i, j)]);
                    res.add(arr[Math.max(i, j)]);
                    return res;
                } 
                // if sum is smaller, move to larger value
                else if (sum < target) {
                    i++;
                } 
                // if sum is larger, move toward smaller value
                else {
                    j++;
                }
            }
        }
		
      	// no pair found
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {-8, 10, 12, -15, 15, 24};
        int target = 0;
        ArrayList<Integer> res = findPair(arr, target);

        for (int ele : res)
            System.out.print(ele + " ");
    }
}
Python
# Python program to find the pair which add up to target 
# in absolute sorted array using two pointers

def findPair(arr, target):
    res = []

    # Case 1: both elements in pair are positive
    i, j = 0, len(arr) - 1
    while i < j:
      
        # skip negative elements 
        if arr[i] < 0:
            i += 1
        elif arr[j] < 0:
            j -= 1
            
        # if both elements are positive check further 
        else:
            sum = arr[i] + arr[j]
            if sum == target:
                res.append(arr[i])
                res.append(arr[j])
                return res
              
            # if sum is smaller, move to larger value
            elif sum < target:
                i += 1
                
            # if sum is larger, move toward smaller value
            else:
                j -= 1

    # Case 2: both elements in pair are negative
    i, j = 0, len(arr) - 1
    while i < j:
      
        # skip positive elements 
        if arr[i] > 0:
            i += 1
        elif arr[j] > 0:
            j -= 1
            
        # if both elements are negative check further 
        else:
            sum = arr[i] + arr[j]
            if sum == target:
                res.append(arr[i])
                res.append(arr[j])
                return res
              
            # if sum is smaller, move to larger value
            elif sum < target:
                j -= 1
                
            # if sum is larger, move toward smaller value
            else:
                i += 1

    # Case 3: one element in pair is positive and other is negative
    i, j = 0, 0
    while i < len(arr) and j < len(arr):
      
        # skip negative elements in arr[i] and skip positive in arr[j]
        if arr[i] < 0:
            i += 1
        elif arr[j] > 0:
            j += 1
            
        # if arr[i] is positive and arr[j] is negative, check further
        else:
            sum = arr[i] + arr[j]
            if sum == target:
                res.append(arr[min(i, j)])
                res.append(arr[max(i, j)])
                return res
              
            # if sum is smaller, move to larger value
            elif sum < target:
                i += 1
                
            # if sum is larger, move toward smaller value
            else:
                j += 1
	
    # no pair exist
    return res

if __name__ == "__main__":
    arr = [-8, 10, 12, -15, 15, 24]
    target = 0
    res = findPair(arr, target)
    print(" ".join(map(str, res)))
C#
// C# program to find the pair which add up to target 
// in absolute sorted array using two pointers

using System;
using System.Collections.Generic;

class GfG {

    static List<int> findPair(int[] arr, int target) {
        List<int> res = new List<int>();

        // Case 1: both elements in pair are positive
        for (int i = 0, j = arr.Length - 1; i < j;) {
          
            // skip negative elements 
            if (arr[i] < 0) {
                i++;
            } else if (arr[j] < 0) {
                j--;
            } 
          
            // if both elements are positive check further 
            else {
                int sum = arr[i] + arr[j];
                if (sum == target) {
                    res.Add(arr[i]);
                    res.Add(arr[j]);
                    return res;
                } 
              
                // if sum is smaller, move to larger value
                else if (sum < target) {
                    i++;
                } 
              
                // if sum is larger, move toward smaller value
                else {
                    j--;
                }
            }
        }

        // Case 2: both elements in pair are negative
        for (int i = 0, j = arr.Length - 1; i < j;) {
          
            // skip positive elements 
            if (arr[i] > 0) {
                i++;
            } else if (arr[j] > 0) {
                j--;
            } 
          
            // if both elements are negative check further 
            else {
                int sum = arr[i] + arr[j];
                if (sum == target) {
                    res.Add(arr[i]);
                    res.Add(arr[j]);
                    return res;
                } 
              
                // if sum is smaller, move to larger value
                else if (sum < target) {
                    j--;
                } 
              
                // if sum is larger, move toward smaller value
                else {
                    i++;
                }
            }
        }

        // Case 3: one element in pair is positive and other is negative
        // i point to positive and j point to negative
        for (int i = 0, j = 0; i < arr.Length && j < arr.Length;) {
          
            // skip negative elements in arr[i] and skip positive in arr[j]
            if (arr[i] < 0) {
                i++;
            } else if (arr[j] > 0) {
                j++;
            } 
          
            // if arr[i] is positive and arr[j] is negative, check further
            else {
                int sum = arr[i] + arr[j];
                if (sum == target) {
                    res.Add(arr[Math.Min(i, j)]);
                    res.Add(arr[Math.Max(i, j)]);
                    return res;
                } 
              
                // if sum is smaller, move to larger value
                else if (sum < target) {
                    i++;
                } 
              
                // if sum is larger, move toward smaller value
                else {
                    j++;
                }
            }
        }

        return res;
    }

    static void Main(string[] args) {
        int[] arr = { -8, 10, 12, -15, 15, 24 };
        int target = 0;
        List<int> res = findPair(arr, target);

        foreach (int ele in res)
            Console.Write(ele + " ");
    }
}
JavaScript
// JavaScript program to find the pair which add up to target 
// in absolute sorted array using two pointers

function findPair(arr, target) {
    let res = [];

    // Case 1: both elements in pair are positive
    for (let i = 0, j = arr.length - 1; i < j;) {
    
        // skip negative elements 
        if (arr[i] < 0) {
            i++;
        } else if (arr[j] < 0) {
            j--;
        } 
        
        // if both elements are positive check further 
        else {
            let sum = arr[i] + arr[j];
            if (sum === target) {
                res.push(arr[i]);
                res.push(arr[j]);
                return res;
            } 
            
            // if sum is smaller, move to larger value
            else if (sum < target) {
                i++;
            } 
            
            // if sum is larger, move toward smaller value
            else {
                j--;
            }
        }
    }

    // Case 2: both elements in pair are negative
    for (let i = 0, j = arr.length - 1; i < j;) {
    
        // skip positive elements 
        if (arr[i] > 0) {
            i++;
        } else if (arr[j] > 0) {
            j--;
        } 
        
        // if both elements are negative check further 
        else {
            let sum = arr[i] + arr[j];
            if (sum === target) {
                res.push(arr[i]);
                res.push(arr[j]);
                return res;
            } 
            
            // if sum is smaller, move to larger value
            else if (sum < target) {
                j--;
            } 
            
            // if sum is larger, move toward smaller value
            else {
                i++;
            }
        }
    }

    // Case 3: one element in pair is positive and other is negative
    // i point to positive and j point to negative
    for (let i = 0, j = 0; i < arr.length && j < arr.length;) {
    
        // skip negative elements in arr[i] and skip positive in arr[j]
        if (arr[i] < 0) {
            i++;
        } else if (arr[j] > 0) {
            j++;
        } 
        
        // if arr[i] is positive and arr[j] is negative, check further
        else {
            let sum = arr[i] + arr[j];
            if (sum === target) {
                res.push(arr[Math.min(i, j)]);
                res.push(arr[Math.max(i, j)]);
                return res;
            } 
            
            // if sum is smaller, move to larger value
            else if (sum < target) {
                i++;
            } 
            
            // if sum is larger, move toward smaller value
            else {
                j++;
            }
        }
    }
	
    // no pair found
    return res;
}

// driver code
let arr = [-8, 10, 12, -15, 15, 24];
let target = 0;
let res = findPair(arr, target);

console.log(res.join(" "));

Output
-15 15 


Next Article
Article Tags :
Practice Tags :

Similar Reads