Open In App

Pair with given Sum (Two Sum)

Last Updated : 28 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array A[] of n numbers and another number x, the task is to check whether or not there exist two elements in A[] whose sum is exactly x. 

Examples: 

Input: arr[] = {0, -1, 2, -3, 1}, x= -2
Output: Yes
Explanation: If we calculate the sum of the output,1 + (-3) = -2

Input: arr[] = {1, -2, 1, 0, 5}, x = 0
Output: No

Recommended Practice

Two Sum using Naive Approach:

The basic approach to solve this problem is by nested traversal.

  • Traverse the array using a loop
  • For each element:
    • Check if there exists another in the array with sum as x
    • Return true if yes, else continue
  • If no such pair is found, return false.

Below is the implementation of the above approach:

C++
// C++ program for the above approach
#include <bits/stdc++.h>

using namespace std;

// Function to find and print pair
bool chkPair(int A[], int size, int x)
{
    for (int i = 0; i < (size - 1); i++) {
        for (int j = (i + 1); j < size; j++) {
            if (A[i] + A[j] == x) {
                return 1;
            }
        }
    }

    return 0;
}

// Driver code
int main()
{
    int A[] = { 0, -1, 2, -3, 1 };
    int x = -2;
    int size = sizeof(A) / sizeof(A[0]);

    if (chkPair(A, size, x)) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << x << endl;
    }

    return 0;
}

// This code is contributed by Samim Hossain Mondal.
C
/*
 * This C program tells if there exists a pair in array
 * whose sum results in x.
 */

#include <stdio.h>

// Function to find and print pair
int chkPair(int A[], int size, int x)
{
    for (int i = 0; i < (size - 1); i++) {
        for (int j = (i + 1); j < size; j++) {
            if (A[i] + A[j] == x) {
                return 1;
            }
        }
    }

    return 0;
}

int main(void)
{
    int A[] = { 0, -1, 2, -3, 1 };
    int x = -2;
    int size = sizeof(A) / sizeof(A[0]);

    if (chkPair(A, size, x)) {
        printf("Yes\n");
    }
    else {
        printf("No\n");
    }

    return 0;
}
// This code is contributed by Manish Kumar (mkumar2789)
Java
// Java program to check if there exists a pair
// in array whose sum results in x.
import java.io.*;
class GFG {

    // Function to find and print pair
    static boolean chkPair(int A[], int size, int x)
    {
        for (int i = 0; i < (size - 1); i++) {
            for (int j = (i + 1); j < size; j++) {
                if (A[i] + A[j] == x) {
                    return true;
                }
            }
        }

        return false;
    }

    public static void main(String[] args)
    {

        int A[] = { 0, -1, 2, -3, 1 };
        int x = -2;
        int size = A.length;

        if (chkPair(A, size, x)) {
            System.out.println("Yes");
        }
        else {
            System.out.println("No");
        }
    }
}

// This code is contributed by umadevi9616
Python
# This python program tells if there exists a pair in array whose sum results in x.

# Function to find and print pair


def chkPair(A, size, x):
    for i in range(0, size - 1):
        for j in range(i + 1, size):
            if (A[i] + A[j] == x):
                return 1
    return 0


if __name__ == "__main__":
    A = [0, -1, 2, -3, 1]
    x = -2
    size = len(A)

    if (chkPair(A, size, x)):
        print("Yes")

    else:
        print("No")

    # This code is contributed by rakeshsahni
C#
// C# program to check if there exists a pair
// in array whose sum results in x.
using System;
class GFG {

    // Function to find and print pair
    static bool chkPair(int[] A, int size, int x)
    {
        for (int i = 0; i < (size - 1); i++) {
            for (int j = (i + 1); j < size; j++) {
                if (A[i] + A[j] == x) {
                    return true;
                }
            }
        }

        return false;
    }

    public static void Main()
    {
        int[] A = { 0, -1, 2, -3, 1 };
        int x = -2;
        int size = A.Length;

        if (chkPair(A, size, x)) {
            Console.WriteLine("Yes");
        }
        else {
            Console.WriteLine("No");
        }
    }
}

// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>

// Javascript program to check if there exists a pair
// in array whose sum results in x. 

// Function to find and print pair
    function chkPair(A , size , x) {
    
        for (i = 0; i < (size - 1); i++) {
            for (j = (i + 1); j < size; j++) {
     
                if (A[i] + A[j] == x) {
                    document.write("Pair with a given sum " + x + " is (" + A[i] + ", " + A[j] + ")");

                    return true;
                }
            }
        }

        return false;
    }

        let A = [ 0, -1, 2, -3, 1 ];
        let x = -2;
        let size = A.length;

        if (chkPair(A, size, x)) {
            document.write("<br/>Valid pair exists");
        }
        else {
            document.write("<br/>No valid pair exists for " + x);
        }


// This code is contributed by Samim Hossain Mondal.
</script>

Output
Yes

Time Complexity: O(N2), Finding pair for every element in the array of size N.
Auxiliary Space: O(1)

Two Sum using Sorting and Two-Pointers technique:

The idea is to use the two-pointer technique. But for using the two-pointer technique, the array must be sorted. Once the array is sorted the two pointers can be taken which mark the beginning and end of the array respectively. If the sum is greater than the sum of those two elements, shift the right pointer to decrease the value of the required sum and if the sum is lesser than the required value, shift the left pointer to increase the value of the required sum.

Illustration:

Let an array be {1, 4, 45, 6, 10, -8} and sum to find be 16
After sorting the array 
A = {-8, 1, 4, 6, 10, 45}
Now, increment ‘l’ when the sum of the pair is less than the required sum and decrement ‘r’ when the sum of the pair is more than the required sum. 
This is because when the sum is less than the required sum then to get the number which could increase the sum of pair, start moving from left to right(also sort the array) thus “l++” and vice versa.
Initialize l = 0, r = 5 
A[l] + A[r] ( -8 + 45) > 16 => decrement r. Now r = 4 
A[l] + A[r] ( -8 + 10) increment l. Now l = 1 
A[l] + A[r] ( 1 + 10) increment l. Now l = 2 
A[l] + A[r] ( 4 + 10) increment l. Now l = 3 
A[l] + A[r] ( 6 + 10) == 16 => Found candidates (return 1)

Note: If there is more than one pair having the given sum then this algorithm reports only one. Can be easily extended for this though. 

Follow the steps below to solve the problem:

  • hasArrayTwoCandidates (A[], ar_size, sum)
  • Sort the array in non-decreasing order.
  • Initialize two index variables to find the candidate 
    elements in the sorted array. 
    • Initialize first to the leftmost index: l = 0
    • Initialize second the rightmost index: r = ar_size-1
  • Loop while l < r. 
    • If (A[l] + A[r] == sum) then return 1
    • Else if( A[l] + A[r] < sum ) then l++
    • Else r–
  • No candidates in the whole array – return 0

Below is the implementation of the above approach:

C++
// C++ program to check if given array
// has 2 elements whose sum is equal
// to the given value

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

// Function to check if array has 2 elements
// whose sum is equal to the given value
bool hasArrayTwoCandidates(int A[], int arr_size, int sum)
{
    int l, r;

    /* Sort the elements */
    sort(A, A + arr_size);

    /* Now look for the two candidates in
       the sorted array*/
    l = 0;
    r = arr_size - 1;
    while (l < r) {
        if (A[l] + A[r] == sum)
            return 1;
        else if (A[l] + A[r] < sum)
            l++;
        else // A[l] + A[r] > sum
            r--;
    }
    return 0;
}

/* Driver program to test above function */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, -8 };
    int n = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);

    // Function calling
    if (hasArrayTwoCandidates(A, arr_size, n))
        cout << "Yes";
    else
        cout << "No";

    return 0;
}
C
// C program to check if given array
// has 2 elements whose sum is equal
// to the given value

#include <stdio.h>
#define bool int

void quickSort(int*, int, int);

bool hasArrayTwoCandidates(int A[], int arr_size, int sum)
{
    int l, r;

    /* Sort the elements */
    quickSort(A, 0, arr_size - 1);

    /* Now look for the two candidates in the sorted
       array*/
    l = 0;
    r = arr_size - 1;
    while (l < r) {
        if (A[l] + A[r] == sum)
            return 1;
        else if (A[l] + A[r] < sum)
            l++;
        else // A[i] + A[j] > sum
            r--;
    }
    return 0;
}

/* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING
    PURPOSE */
void exchange(int* a, int* b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

int partition(int A[], int si, int ei)
{
    int x = A[ei];
    int i = (si - 1);
    int j;

    for (j = si; j <= ei - 1; j++) {
        if (A[j] <= x) {
            i++;
            exchange(&A[i], &A[j]);
        }
    }
    exchange(&A[i + 1], &A[ei]);
    return (i + 1);
}

/* Implementation of Quick Sort
A[] --> Array to be sorted
si  --> Starting index
ei  --> Ending index
*/
void quickSort(int A[], int si, int ei)
{
    int pi; /* Partitioning index */
    if (si < ei) {
        pi = partition(A, si, ei);
        quickSort(A, si, pi - 1);
        quickSort(A, pi + 1, ei);
    }
}

/* Driver program to test above function */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, -8 };
    int n = 16;
    int arr_size = 6;

    if (hasArrayTwoCandidates(A, arr_size, n))
        printf("Yes");
    else
        printf("No");

    getchar();
    return 0;
}
Java
// Java program to check if given array
// has 2 elements whose sum is equal
// to the given value
import java.util.*;

class GFG {
    // Function to check if array has 2 elements
    // whose sum is equal to the given value
    static boolean
    hasArrayTwoCandidates(int A[], int arr_size, int sum)
    {
        int l, r;

        /* Sort the elements */
        Arrays.sort(A);

        /* Now look for the two candidates
        in the sorted array*/
        l = 0;
        r = arr_size - 1;
        while (l < r) {
            if (A[l] + A[r] == sum)
                return true;
            else if (A[l] + A[r] < sum)
                l++;
            else // A[i] + A[j] > sum
                r--;
        }
        return false;
    }

    // Driver code
    public static void main(String args[])
    {
        int A[] = { 1, 4, 45, 6, 10, -8 };
        int n = 16;
        int arr_size = A.length;

        // Function calling
        if (hasArrayTwoCandidates(A, arr_size, n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python
# Python program to check for the sum condition to be satisfied

def hasArrayTwoCandidates(A, arr_size, sum):
    # sort the array
    quickSort(A, 0, arr_size-1)
    l = 0
    r = arr_size-1

    # traverse the array for the two elements
    while l < r:
        if (A[l] + A[r] == sum):
            return 1
        elif (A[l] + A[r] < sum):
            l += 1
        else:
            r -= 1
    return 0

# Implementation of Quick Sort
# A[] --> Array to be sorted
# si --> Starting index
# ei --> Ending index

def quickSort(A, si, ei):
    if si < ei:
        pi = partition(A, si, ei)
        quickSort(A, si, pi-1)
        quickSort(A, pi + 1, ei)

# Utility function for partitioning
# the array(used in quick sort)

def partition(A, si, ei):
    x = A[ei]
    i = (si - 1)
    for j in range(si, ei):
        if A[j] <= x:
            i += 1
            # This operation is used to swap two variables in Python
            A[i], A[j] = A[j], A[i]

    A[i + 1], A[ei] = A[ei], A[i + 1]
    return i + 1

# Driver program to test the functions
A = [1, 4, 45, 6, 10, -8]
n = 16
if (hasArrayTwoCandidates(A, len(A), n)):
    print("Yes")
else:
    print("No")

# This code is contributed by __Devesh Agrawal__
C#
// C# program to check for pair
// in A[] with sum as x

using System;

class GFG {
    static bool hasArrayTwoCandidates(int[] A, int arr_size,
                                      int sum)
    {
        int l, r;

        /* Sort the elements */
        sort(A, 0, arr_size - 1);

        /* Now look for the two candidates
        in the sorted array*/
        l = 0;
        r = arr_size - 1;
        while (l < r) {
            if (A[l] + A[r] == sum)
                return true;
            else if (A[l] + A[r] < sum)
                l++;
            else // A[i] + A[j] > sum
                r--;
        }
        return false;
    }

    /* Below functions are only to sort the
    array using QuickSort */

    /* This function takes last element as pivot,
    places the pivot element at its correct
    position in sorted array, and places all
    smaller (smaller than pivot) to left of
    pivot and all greater elements to right
    of pivot */
    static int partition(int[] arr, int low, int high)
    {
        int pivot = arr[high];

        // index of smaller element
        int i = (low - 1);
        for (int j = low; j <= high - 1; j++) {
            // If current element is smaller
            // than or equal to pivot
            if (arr[j] <= pivot) {
                i++;

                // swap arr[i] and arr[j]
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        // swap arr[i+1] and arr[high] (or pivot)
        int temp1 = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp1;

        return i + 1;
    }

    /* The main function that
    implements QuickSort()
    arr[] --> Array to be sorted,
    low --> Starting index,
    high --> Ending index */
    static void sort(int[] arr, int low, int high)
    {
        if (low < high) {
            /* pi is partitioning index, arr[pi]
            is now at right place */
            int pi = partition(arr, low, high);

            // Recursively sort elements before
            // partition and after partition
            sort(arr, low, pi - 1);
            sort(arr, pi + 1, high);
        }
    }

    // Driver code
    public static void Main()
    {
        int[] A = { 1, 4, 45, 6, 10, -8 };
        int n = 16;
        int arr_size = 6;

        if (hasArrayTwoCandidates(A, arr_size, n))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}

// This code is contributed by Sam007
JavaScript
<script>

// Javascript program to check if given array
// has 2 elements whose sum is equal
// to the given value

// Function to check if array has 2 elements
// whose sum is equal to the given value
function hasArrayTwoCandidates(A, arr_size, sum)
{
    var l, r;

    /* Sort the elements */
    A.sort();

    /* Now look for the two candidates in
    the sorted array*/
    l = 0;
    r = arr_size - 1;
    while (l < r) {
        if (A[l] + A[r] == sum)
            return 1;
        else if (A[l] + A[r] < sum)
            l++;
        else // A[i] + A[j] > sum
            r--;
    }
    return 0;
}

/* Driver program to test above function */
var A = [ 1, 4, 45, 6, 10, -8 ]
var n = 16;
var arr_size = A.length;
// Function calling
if (hasArrayTwoCandidates(A, arr_size, n))
    document.write("Array has two elements" +
            " with the given sum");
else
    document.write("Array doesn't have two" +
            " elements with the given sum");

</script>
PHP
<?php
// PHP program to check if given 
// array has 2 elements whose sum 
// is equal to the given value

// Function to check if array has 
// 2 elements whose sum is equal
// to the given value
function hasArrayTwoCandidates($A, $arr_size,
                                        $sum)
{
    $l; $r;

    /* Sort the elements */
    //sort($A, A + arr_size);
    sort($A);

    /* Now look for the two candidates 
    in the sorted array*/
    $l = 0;
    $r = $arr_size - 1; 
    while ($l < $r)
    {
        if($A[$l] + $A[$r] == $sum)
            return 1; 
        else if($A[$l] + $A[$r] < $sum)
            $l++;
        else // A[i] + A[j] > sum
            $r--;
    } 
    return 0;
}

// Driver Code
$A = array (1, 4, 45, 6, 10, -8);
$n = 16;
$arr_size = sizeof($A);

// Function calling
if(hasArrayTwoCandidates($A, $arr_size, $n))
    echo "Yes";
else
    echo "No";
    
// This code is contributed by m_kit
?>

Output
Yes

Time Complexity: O(NlogN), Time complexity for sorting the array
Auxiliary Space: O(1)

Two Sum using Binary Search:

Sort the array, then traverse the array elements and perform binary search for (target – a[i]) on the remaining part

Follow the below steps to solve the problem:

  • Sort the array in non-decreasing order.
  • Traverse from 0 to N-1
    • Initialize searchKey = sum – A[i]
    • If(binarySearch(searchKey, A, i + 1, N) == True
      • Return True
  • Return False

Below is the implementation of the above approach:

C++
// C++ program to check if given array
// has 2 elements whose sum is equal
// to the given value

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

bool binarySearch(int A[], int low, int high, int searchKey)
{

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

        // Check if searchKey is present at mid
        if (A[m] == searchKey)
            return true;

        // If searchKey greater, ignore left half
        if (A[m] < searchKey)
            low = m + 1;

        // If searchKey is smaller, ignore right half
        else
            high = m - 1;
    }

    // if we reach here, then element was
    // not present
    return false;
}

bool checkTwoSum(int A[], int arr_size, int sum)
{
    int l, r;

    /* Sort the elements */
    sort(A, A + arr_size);

    // Traversing all element in an array search for
    // searchKey
    for (int i = 0; i < arr_size - 1; i++) {

        int searchKey = sum - A[i];
        // calling binarySearch function
        if (binarySearch(A, i + 1, arr_size - 1, searchKey)
            == true) {
            return true;
        }
    }
    return false;
}

/* Driver program to test above function */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, -8 };
    int n = 14;
    int arr_size = sizeof(A) / sizeof(A[0]);

    // Function calling
    if (checkTwoSum(A, arr_size, n))
        cout << "Yes";
    else
        cout << "No";

    return 0;
}
Java
// Java program to check if given array
// has 2 elements whose sum is equal
// to the given value
import java.util.*;

class GFG {

    static boolean binarySearch(int A[], int low, int high,
                                int searchKey)
    {

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

            // Check if searchKey is present at mid
            if (A[m] == searchKey)
                return true;

            // If searchKey greater, ignore left half
            if (A[m] < searchKey)
                low = m + 1;

            // If searchKey is smaller, ignore right half
            else
                high = m - 1;
        }

        // if we reach here, then element was
        // not present
        return false;
    }

    static boolean checkTwoSum(int A[], int arr_size,
                               int sum)
    {
        int l, r;

        /* Sort the elements */
        Arrays.sort(A);

        // Traversing all element in an array search for
        // searchKey

        for (int i = 0; i < arr_size - 1; i++) {

            int searchKey = sum - A[i];

            if (binarySearch(A, i + 1, arr_size - 1,
                             searchKey)
                == true) {
                return true;
            }
        }

        return false;
    }

    // Driver code
    public static void main(String args[])
    {
        int A[] = { 1, 4, 45, 6, 10, -8 };
        int n = 14;
        int arr_size = A.length;

        // Function calling
        if (checkTwoSum(A, arr_size, n))
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python
# Python program to check for the sum
# condition to be satisfied


def binarySearch(A, low, high, searchKey):
    m = 0
    while (low <= high):
        m = (high + low) // 2
        # Check if searchKey is present at mid
        if (A[m] == searchKey):
            return 1
        # If searchKey greater, ignore left half
        if (A[m] < searchKey):
            low = m + 1
        # If searchKey is smaller, ignore right half
        else:
            high = m - 1
    # if we reach here, then element was
    # not present
    return 0


def checkTwoSum(A, arr_size, sum):

    # sort the array
    A.sort()
    l = 0
    r = arr_size-1

    #  Traversing all element in an array search for searchKey
    i = 0
    while i < arr_size-1:
        searchKey = sum-A[i]
        # calling binarySearch function
        if(binarySearch(A, i+1, r, searchKey) == 1):
            return 1
        i = i+1

    return 0


# Driver program to test the functions
A = [1, 4, 45, 6, 10, -8]
n = 14
if (checkTwoSum(A, len(A), n)):
    print("Yes")
else:
    print("No")
C#
// C# program to check for pair
// in A[] with sum as x
using System;
using System.Collections.Generic;
class GFG {
  static bool binarySearch(int[] A, int low, int high,
                           int searchKey)
  {

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

      // Check if searchKey is present at mid
      if (A[m] == searchKey)
        return true;

      // If searchKey greater, ignore left half
      if (A[m] < searchKey)
        low = m + 1;

      // If searchKey is smaller, ignore right half
      else
        high = m - 1;
    }

    // if we reach here, then element was
    // not present
    return false;
  }
  static bool checkTwoSum(int[] A, int arr_size, int sum)
  {

    Array.Sort(A);

    // Traversing all element in an array search for
    // searchKey
    for (int i = 0; i < arr_size - 1; i++) {

      int searchKey = sum - A[i];
      // calling binarySearch function
      if (binarySearch(A, i + 1, arr_size - 1,
                       searchKey)
          == true) {
        return true;
      }
    }
    return false;
  }

  // Driver code
  public static void Main()
  {
    int[] A = { 1, 4, 45, 6, 10, -8 };
    int n = 16;
    int arr_size = 6;

    if (checkTwoSum(A, arr_size, n))
      Console.Write("Yes");
    else
      Console.Write("No");
  }
}

// This code is contributed by garg28harsh.
JavaScript
function binarySearch( A,  low,  high,  searchKey)
{

    while (low <= high) {
        let m = low + (high - low) / 2;

        // Check if searchKey is present at mid
        if (A[m] == searchKey)
            return true;

        // If searchKey greater, ignore left half
        if (A[m] < searchKey)
            low = m + 1;

        // If searchKey is smaller, ignore right half
        else
            high = m - 1;
    }

    // if we reach here, then element was
    // not present
    return false;
}

function checkTwoSum( A,  arr_size, sum)
{
    
    /* Sort the elements */
    A.sort();

    // Traversing all element in an array search for
    // searchKey
    for (let i = 0; i < arr_size - 1; i++) {

        let searchKey = sum - A[i];
        // calling binarySearch function
        if (binarySearch(A, i + 1, arr_size - 1, searchKey) == true) {
            return true;
        }
    }
    return false;
}

/* Driver program to test above function */
    let A = [ 1, 4, 45, 6, 10, -8 ];
    let n = 14;
    let arr_size = 6;

    // Function calling
    if (checkTwoSum(A, arr_size, n))
        console.log( "Yes");
    else
       console.log("No");
       
       // This code is contributed by garg28harsh.

Output
Yes

Time Complexity: O(NlogN)
Auxiliary Space: O(1)

Two Sum using Hashing:

This problem can be solved efficiently by using the technique of hashing. Use a hash_map to check for the current array value x(let), if there exists a value target_sum-x which on adding to the former gives target_sum. This can be done in constant time.

Illustration:

arr[] = {0, -1, 2, -3, 1} 
sum = -2 
Now start traversing: 
Step 1: For ‘0’ there is no valid number ‘-2’ so store ‘0’ in hash_map. 
Step 2: For ‘-1’ there is no valid number ‘-1’ so store ‘-1’ in hash_map. 
Step 3: For ‘2’ there is no valid number ‘-4’ so store ‘2’ in hash_map. 
Step 4: For ‘-3’ there is no valid number ‘1’ so store ‘-3’ in hash_map. 
Step 5: For ‘1’ there is a valid number ‘-3’ so answer is 1, -3 

unordered_set s

for(i=0 to end)

  if(s.find(target_sum – arr[i]) == s.end)

    insert(arr[i] into s)

  else 

    print arr[i], target-arr[i]

Follow the steps below to solve the problem:

  • Initialize an empty hash table s.
  • Do the following for each element A[i] in A[] 
    • If s[x – A[i]] is set then print the pair (A[i], x – A[i])
    • Insert A[i] into s.

Below is the implementation of the above approach:

C++
// C++ program to check if given array
// has 2 elements whose sum is equal
// to the given value
#include <bits/stdc++.h>

using namespace std;

void printPairs(int arr[], int arr_size, int sum)
{
    unordered_set<int> s;
    for (int i = 0; i < arr_size; i++) {
        int temp = sum - arr[i];

        if (s.find(temp) != s.end()) {
            cout << "Yes" << endl;
            return;
        }
        s.insert(arr[i]);
    }
    cout << "No" << endl;
}

/* Driver Code */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, 8 };
    int n = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);

    // Function calling
    printPairs(A, arr_size, n);

    return 0;
}
C
// C program to check if given array
// has 2 elements whose sum is equal
// to the given value

#include <stdio.h>
#define MAX 100000

// NOTE: Works only if range elements is limited
// target - arr[i] >= 0 && target - arr[i] < MAX

void printPairs(int arr[], int arr_size, int target)
{
    int i, temp;

    /*initialize hash set as 0*/
    int s[MAX] = { 0 };

    for (i = 0; i < arr_size; i++) {
        temp = target - arr[i];
        if (s[temp] == 1) {
            printf("Yes");
            return;
        }
        s[arr[i]] = 1;
    }

    printf("No");
}

/* Driver Code */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, 8 };
    int target = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);

    printPairs(A, arr_size, target);

    getchar();
    return 0;
}
Java
// Java implementation using Hashing
import java.io.*;
import java.util.HashSet;

class PairSum {
    static void printpairs(int arr[], int sum)
    {
        HashSet<Integer> s = new HashSet<Integer>();
        for (int i = 0; i < arr.length; ++i) {
            int temp = sum - arr[i];

            // checking for condition
            if (s.contains(temp)) {
                System.out.println("Yes");
                return;
            }
            s.add(arr[i]);
        }
        System.out.println("No");
    }

    // Driver Code
    public static void main(String[] args)
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        printpairs(A, n);
    }
}

// This article is contributed by Aakash Hasija
Python
# Python program to find if there are
# two elements with given sum

# function to check for the given sum
# in the array


def printPairs(arr, arr_size, sum):

    # Create an empty hash map
    # using an hashmap allows us to store the indices
    hashmap = {}

    for i in range(0, arr_size):
        temp = sum-arr[i]
        if (temp in hashmap):
            print('Yes')
            return
        hashmap[arr[i]] = i
    print("No")


# driver code
A = [1, 4, 45, 6, 10, 8]
n = 16
printPairs(A, len(A), n)

# This code will also work in case the array has the same number twice
# and target is the sum of those numbers
# Eg: Array = [4,6,4] Target = 8

# This code is contributed by __Achyut Upadhyay__
C#
// C# implementation using Hashing
using System;
using System.Collections.Generic;

class GFG {
    static void printpairs(int[] arr, int sum)
    {
        HashSet<int> s = new HashSet<int>();
        for (int i = 0; i < arr.Length; ++i) {
            int temp = sum - arr[i];

            // checking for condition
            if (s.Contains(temp)) {
                Console.Write("Yes");
                return;
            }
            s.Add(arr[i]);
        }
        Console.Write("No");
    }

    // Driver Code
    static void Main()
    {
        int[] A = new int[] { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        printpairs(A, n);
    }
}

// This code is contributed by
// Manish Shaw(manishshaw1)
JavaScript
<script>


// JavaScript program to check if given array
// has 2 elements whose sum is equal
// to the given value

// Javascript implementation using Hashing

    function printpairs(arr, sum)
    {
        let s = new Set();
        for (let i = 0; i < arr.length; ++i) 
        {
            let temp = sum - arr[i];

            // checking for condition
            if (s.has(temp)) {
                document.write(
                    "Pair with given sum "
                    + sum + " is (" + arr[i]
                    + ", " + temp + ")");
            }
            s.add(arr[i]);
        }
    }

// Driver Code

        let A = [ 1, 4, 45, 6, 10, 8 ];
        let n = 16;
        printpairs(A, n);

</script>

Output
Yes

Time Complexity: O(N), As the whole array is needed to be traversed only once.
Auxiliary Space: O(N), A hash map has been used to store array elements.

Note: The solution will work even if the range of numbers includes negative numbers + if the pair is formed by numbers recurring twice in array eg: array = [3,4,3]; pair = (3,3); target sum = 6.

Two Sum Using remainders of the elements less than x:

The idea is to count the elements with remainders when divided by x, i.e 0 to x-1, each remainder separately. Suppose we have x as 6, then the numbers which are less than 6 and have remainders which add up to 6 gives sum as 6 when added. For example, we have elements, 2,4 in the array and 2%6 = 2 and 4%6 =4, and these remainders add up to give 6. Like that we have to check for pairs with remainders (1,5),(2,4),(3,3). if we have one or more elements with remainder 1 and one or more elements with remainder 5, then surely we get a sum as 6. Here we do not consider (0,6) as the elements for the resultant pair should be less than 6. when it comes to (3,3) we have to check if we have two elements with remainder 3, then we can say that “There exists a pair whose sum is x”. 

Follow the steps below to solve the problem:

  • 1. Create an array with size x. 
  • 2. Initialize all rem elements to zero.
  • 3. Traverse the given array
  • Do the following if arr[i] is less than x:
    • r=arr[i]%x which is done to get the remainder.
    • rem[r]=rem[r]+1 i.e. increasing the count of elements that have remainder r when divided with x.
  • 4. Now, traverse the rem array from 1 to x/2.   
  • If(rem[i]> 0 and rem[x-i]>0) then print “YES” and come out of the loop. This means that we have a pair that results in x upon doing.
  • 5. Now when we reach at x/2 in the above loop   
  • If x is even, for getting a pair we should have two elements with remainder x/2.
    • If rem[x/2]>1 then print “YES” else print “NO”
  • If it is not satisfied that is x is odd, it will have a separate pair with x-x/2.
    • If rem[x/2]>0 and rem[x-x/2]>0 , then print “Yes” else, print”No”;

Below is the implementation of the above approach:

C++
// Code in cpp to tell if there exists a pair in array whose
// sum results in x.
#include <iostream>
using namespace std;

// Function to print pairs
void printPairs(int a[], int n, int x)
{
    int i;
    int rem[x];
    // initializing the rem values with 0's.
    for (i = 0; i < x; i++)
        rem[i] = 0;
    // Perform the remainder operation only if the element
    // is x, as numbers greater than x can't be used to get
    // a sum x. Updating the count of remainders.
    for (i = 0; i < n; i++)
        if (a[i] < x)
            rem[a[i] % x]++;

    // Traversing the remainder list from start to middle to
    // find pairs
    for (i = 1; i < x / 2; i++) {
        if (rem[i] > 0 && rem[x - i] > 0) {
            // The elements with remainders i and x-i will
            // result to a sum of x. Once we get two
            // elements which add up to x , we print x and
            // break.
            cout << "Yes\n";
            break;
        }
    }

    // Once we reach middle of remainder array, we have to
    // do operations based on x.
    if (i >= x / 2) {
        if (x % 2 == 0) {
            // if x is even and we have more than 1 elements
            // with remainder x/2, then we will have two
            // distinct elements which add up to x. if we
            // dont have more than 1 element, print "No".
            if (rem[x / 2] > 1)
                cout << "Yes\n";
            else
                cout << "No\n";
        }
        else {
            // When x is odd we continue the same process
            // which we did in previous loop.
            if (rem[x / 2] > 0 && rem[x - x / 2] > 0)
                cout << "Yes\n";
            else
                cout << "No\n";
        }
    }
}

/* Driver Code */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, 8 };
    int n = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);

    // Function calling
    printPairs(A, arr_size, n);

    return 0;
}

// This code is contributed by Aditya Kumar (adityakumar129)
C
// Code in c to tell if there exists a pair in array whose
// sum results in x.
#include <stdio.h>

// Function to print pairs
void printPairs(int a[], int n, int x)
{
    int i;
    int rem[x];
    // initializing the rem values with 0's.
    for (i = 0; i < x; i++)
        rem[i] = 0;
    // Perform the remainder operation only if the element
    // is x, as numbers greater than x can't be used to get
    // a sum x. Updating the count of remainders.
    for (i = 0; i < n; i++)
        if (a[i] < x)
            rem[a[i] % x]++;

    // Traversing the remainder list from start to middle to
    // find pairs
    for (i = 1; i < x / 2; i++) {
        if (rem[i] > 0 && rem[x - i] > 0) {
            // The elements with remainders i and x-i will
            // result to a sum of x. Once we get two
            // elements which add up to x , we print x and
            // break.
            printf("Yes\n");
            break;
        }
    }

    // Once we reach middle of remainder array, we have to
    // do operations based on x.
    if (i >= x / 2) {
        if (x % 2 == 0) {
            // if x is even and we have more than 1 elements
            // with remainder x/2, then we will have two
            // distinct elements which add up to x. if we
            // dont have more than 1 element, print "No".
            if (rem[x / 2] > 1)
                printf("Yes\n");
            else
                printf("No\n");
        }
        else {
            // When x is odd we continue the same process
            // which we did in previous loop.
            if (rem[x / 2] > 0 && rem[x - x / 2] > 0)
                printf("Yes\n");
            else
                printf("No\n");
        }
    }
}

/* Driver Code */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, 8 };
    int n = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);

    // Function calling
    printPairs(A, arr_size, n);

    return 0;
}

// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Code in Java to tell if there exists a pair in array
// whose sum results in x.
import java.util.*;

class GFG {

    // Function to print pairs
    static void printPairs(int a[], int n, int x)
    {
        int i;
        int[] rem = new int[x];
        // initializing the rem values with 0's.
        for (i = 0; i < x; i++)
            rem[i] = 0;
        // Perform the remainder operation only if
        // the element is x, as numbers greater than
        // x can't be used to get a sum x. Updating
        // the count of remainders.
        for (i = 0; i < n; i++)
            if (a[i] < x)
                rem[a[i] % x]++;

        // Traversing the remainder list from start to
        // middle to find pairs
        for (i = 1; i < x / 2; i++) {
            if (rem[i] > 0 && rem[x - i] > 0) {
                // The elements with remainders i and x-i
                // will result to a sum of x. Once we get
                // two elements which add up to x , we print
                // x and break.
                System.out.println("Yes");
                break;
            }
        }

        // Once we reach middle of remainder array, we have
        // to do operations based on x.
        if (i >= x / 2) {
            if (x % 2 == 0) {
                // if x is even and we have more than 1
                // elements with remainder x/2, then we
                // will have two distinct elements which
                // add up to x. if we dont have more
                // than 1 element, print "No".
                if (rem[x / 2] > 1)
                    System.out.println("Yes");
                else
                    System.out.println("No");
            }
            else {

                // When x is odd we continue the same
                // process which we did in previous loop.
                if (rem[x / 2] > 0 && rem[x - x / 2] > 0)
                    System.out.println("Yes");
                else
                    System.out.println("No");
            }
        }
    }

    /* Driver Code */
    public static void main(String[] args)
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = A.length;

        // Function calling
        printPairs(A, arr_size, n);
    }
}

// This code is contributed by Aditya Kumar (adityakumar129)
Python
# Code in Python3 to tell if there
# exists a pair in array whose
# sum results in x.

# Function to print pairs


def printPairs(a, n, x):

    rem = []

    for i in range(x):

        # Initializing the rem
        # values with 0's.
        rem.append(0)

    for i in range(n):
        if (a[i] < x):

            # Perform the remainder operation
            # only if the element is x, as
            # numbers greater than x can't
            # be used to get a sum x.Updating
            # the count of remainders.
            rem[a[i] % x] += 1

    # Traversing the remainder list from
    # start to middle to find pairs
    for i in range(1, x // 2):
        if (rem[i] > 0 and rem[x - i] > 0):

            # The elements with remainders
            # i and x-i will result to a
            # sum of x. Once we get two
            # elements which add up to x,
            # we print x and break.
            print("Yes")
            break

    # Once we reach middle of
    # remainder array, we have to
    # do operations based on x.
    if (i >= x // 2):
        if (x % 2 == 0):
            if (rem[x // 2] > 1):

                # If x is even and we have more
                # than 1 elements with remainder
                # x/2, then we will have two
                # distinct elements which add up
                # to x. if we dont have than 1
                # element, print "No".
                print("Yes")
            else:
                print("No")
        else:

            # When x is odd we continue
            # the same process which we
            # did in previous loop.
            if (rem[x // 2] > 0 and
                    rem[x - x // 2] > 0):
                print("Yes")
            else:
                print("No")


# Driver Code
A = [1, 4, 45, 6, 10, 8]
n = 16
arr_size = len(A)

# Function calling
printPairs(A, arr_size, n)

# This code is contributed by subhammahato348
C#
// C# Code in C# to tell if there
// exists a pair in array whose
// sum results in x.
using System;
class GFG {

    // Function to print pairs
    static void printPairs(int[] a, int n, int x)
    {
        int i;
        int[] rem = new int[x];
        for (i = 0; i < x; i++) {

            // initializing the rem
            // values with 0's.
            rem[i] = 0;
        }
        for (i = 0; i < n; i++) {
            if (a[i] < x) {

                // Perform the remainder
                // operation only if the
                // element is x, as numbers
                // greater than x can't
                // be used to get a sum x.
                // Updating the count of remainders.
                rem[a[i] % x]++;
            }
        }

        // Traversing the remainder list
        // from start to middle to
        // find pairs
        for (i = 1; i < x / 2; i++) {
            if (rem[i] > 0 && rem[x - i] > 0) {

                // The elements with remainders
                // i and x-i will
                // result to a sum of x.
                // Once we get two
                // elements which add up to x ,
                // we print x and
                // break.
                Console.Write("Yes"
                              + "\n");
                break;
            }
        }

        // Once we reach middle of
        // remainder array, we have to
        // do operations based on x.
        if (i >= x / 2) {
            if (x % 2 == 0) {
                if (rem[x / 2] > 1) {

                    // if x is even and
                    // we have more than 1
                    // elements with remainder
                    // x/2, then we will
                    // have two distinct elements
                    // which add up
                    // to x. if we dont have
                    // more than 1
                    // element, print "No".
                    Console.Write("Yes"
                                  + "\n");
                }
                else {
                    Console.Write("No"
                                  + "\n");
                }
            }
            else {

                // When x is odd we continue
                // the same process
                // which we did in previous loop.
                if (rem[x / 2] > 0 && rem[x - x / 2] > 0) {
                    Console.Write("Yes"
                                  + "\n");
                }
                else {
                    Console.WriteLine("No"
                                      + "\n");
                }
            }
        }
    }

    /* Driver Code */
    public static void Main(string[] args)
    {
        int[] A = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = A.Length;

        // Function calling
        printPairs(A, arr_size, n);
    }
}

// This code is contributed by SoumikMondal
JavaScript
<script>

// Code in Javascript to tell if there 
// exists a pair in array whose
// sum results in x.

// Function to print pairs
function printPairs(a, n, x)
{
    let i;
    let rem = new Array(x);
    for(i = 0; i < x; i++)
    {
    
        // Initializing the rem
        // values with 0's.
        rem[i] = 0;
    }
    for(i = 0; i < n; i++)
    {
        if (a[i] < x)
        {
        
            // Perform the remainder
            // operation only if the
            // element is x, as numbers
            // greater than x can't
            // be used to get a sum x.
            // Updating the count of remainders.
            rem[a[i] % x]++;
        }
    }
    
    // Traversing the remainder list
    // from start to middle to
    // find pairs
    for(i = 1; i < x / 2; i++)
    {
        if (rem[i] > 0 && rem[x - i] > 0)
        {
            
            // The elements with remainders
            // i and x-i will
            // result to a sum of x.
            // Once we get two
            // elements which add up to x ,
            // we print x and
            // break.
            document.write("Yes" + "</br>");
            break;
        }
    }
    
    // Once we reach middle of
    // remainder array, we have to
    // do operations based on x.
    if (i >= x / 2)
    {
        if (x % 2 == 0)
        {
            if (rem[x / 2] > 1)
            {
            
                // If x is even and
                // we have more than 1
                // elements with remainder
                // x/2, then we will
                // have two distinct elements
                // which add up
                // to x. if we dont have
                //more than 1
                // element, print "No".
                document.write("Yes" + "</br>");
            }
            else
            {
                document.write("No" + "</br>");
            }
        }
        else
        {
        
            // When x is odd we continue
            // the same process
            // which we did in previous loop.
            if (rem[x / 2] > 0 &&
                rem[x - x / 2] > 0)
            {
                document.write("Yes" + "</br>");
            }
            else
            {
                document.write("No" + "</br>");
            }
        }
    }
}
  
// Driver code    
let A = [ 1, 4, 45, 6, 10, 8 ];
let n = 16;
let arr_size = A.length;

// Function calling
printPairs(A, arr_size, n);

// This code is contributed by suresh07

</script>

Output
Yes

Time Complexity: O(N+X), Traversing over the array of size N and Checking for remainders till X
Auxiliary Space: O(X), Space for storing remainders

Related Problems:  

Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem. 



Previous Article
Next Article

Similar Reads

Queries to check if any pair exists in an array having values at most equal to the given pair
Given a vector of pairs arr[] and Q queries in the form of pairs in an array Queries[], the task for each query is to check if there exists any pair with both the values smaller than those in the pair of the current query. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[][] = {{3, 5}, {2, 7}, {2, 3}, {4, 9}}, Quer
12 min read
Kth smallest pair and number of pairs less than a given pair (x, y)
Given N pairs, the task is to find the Kth smallest pair and the number of pairs less than the given pair (x, y). Examples: Input: pairs[][] = {{23, 20}, {23, 10}, {23, 30}, {12, 35}, {12, 22}}, K = 3, (x, y) = (23, 20) Output: {23, 10} 3 Input: pairs[][] = {{23, 20}, {23, 10}, {23, 30}, {12, 35}, {12, 22}}, K = 2, (x, y) = (12, 35) Output: {12, 35
10 min read
Pair with given product | Set 1 (Find if any pair exists)
Given an array of distinct elements and a number x, find if there is a pair with a product equal to x. Examples : Input : arr[] = {10, 20, 9, 40}; int x = 400;Output : YesInput : arr[] = {10, 20, 9, 40}; int x = 190;Output : NoInput : arr[] = {-10, 20, 9, -40}; int x = 400;Output : YesInput : arr[] = {-10, 20, 9, 40}; int x = -400;Output : YesInput
15+ min read
Pair formation such that maximum pair sum is minimized
Given an array of size 2 * N integers. Divide the array into N pairs, such that the maximum pair sum is minimized. In other words, the optimal division of array into N pairs should result into a maximum pair sum which is minimum of other maximum pair sum of all possibilities. Examples: Input : N = 2 , arr[] = { 5, 8, 3, 9 } Output : (3, 9) (5, 8) E
5 min read
Pair the integers of Array so that each pair sum is consecutive and distinct
Given an array arr[]of size N. We have to pair the integers such that each integer should be in exactly one pair and each sum of pairs is consecutive and distinct. Formally, sum(arri + arrj) + 1 = sum(arri1 + arrj1). Print the pairs of integers satisfying all the conditions. If it is not possible to find the pairs return -1. Examples: Input: N = 6,
7 min read
Number of indices pair such that element pair sum from first Array is greater than second Array
Given two integer arrays A[] and B[] of equal sizes, the task is to find the number of pairs of indices {i, j} in the arrays such that A[i] + A[j] &gt; B[i] + B[j] and i &lt; j.Examples: Input: A[] = {4, 8, 2, 6, 2}, B[] = {4, 5, 4, 1, 3} Output: 7 Explanation: There are a total of 7 pairs of indices {i, j} in the array following the condition. The
15+ min read
Pair with given sum in sorted array (Two Sum II)
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 &lt;= index1 &lt; index2 &lt;= numbers.length. Return the indices of the two numbers, index1 and index2, added by one as
5 min read
Maximize value of a pair from two given arrays based on given conditions
Given two arrays A[] and B[] consisting of N integers and an integer K, the task is to find the maximum value of B[i] + B[j] + abs(A[i] - A[j]) by choosing any pair (i, j) such that abs(A[i] - A[j]) ? K. Examples: Input: A[] = {5, 6, 9, 10}, B[] = {3, 0, 10, -10}, K = 1Output: 4Explanation:Only two pairs can be chosen, i.e. (0, 1) and (2, 3), becau
15+ min read
Probability of a random pair being the maximum weighted pair
Given two arrays A and B, a random pair is picked having an element from array A and another from array B. Output the probability of the pair being maximum weighted. Examples: Input : A[] = 1 2 3 B[] = 1 3 3 Output : 0.222 Explanation : Possible pairs are : {1, 1}, {1, 3}, {1, 3}, {2, 1}, {2, 3}, {2, 3}, {3, 1}, {3, 3}, {3, 3} i.e. 9. The pair with
7 min read
Store duplicate keys-values pair and sort the key-value pair by key
Given N key-value pairs that contain duplicate keys and values, the task is to store these pairs and sort the pairs by key. Examples: Input : N : 10 Keys : 5 1 4 6 8 0 6 6 5 5 values: 0 1 2 3 4 5 6 7 8 9 Output : Keys : 0 1 4 5 5 5 6 6 6 8 values: 5 1 2 0 8 9 3 6 7 4 Explanation: We have given 10 key, value pairs which contain duplicate keys and va
12 min read
three90RightbarBannerImg