Kiến thức

Given an array A[] and a number x, check for pair in A[] with sum as x-GeeksforGeeks

Given an array A[] and a number x, check for pair in A[] with sum as x
  • Difficulty Level :

    Easy

  • Last Updated : 01 Jun, 2021

Write a program that, given an array A[] of n numbers and another number x, determines whether or not there exist two elements in S whose sum is exactly x. 

Examples: 

Input: arr[] = {0, -1, 2, -3, 1} sum = -2 Output: -3, 1 If we calculate the sum of the output, 1 + (-3) = -2 Input: arr[] = {1, -2, 1, 0, 5} sum = 0 Output: -1 No valid pair exists.

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

Method 1: Sorting and Two-Pointers technique.

Approach: A tricky approach to solve this problem can be to use the two-pointer technique. But for using 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 required sum and if the sum is lesser than the required value, shift the left pointer to increase the value of the required sum. Let’s understand this using an example.

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. 

Algorithm: 

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

Bạn đang xem: Given an array A[] and a number x, check for pair in A[] with sum as x-GeeksforGeeks

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[i] + A[j] > 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 << "Array has two elements"
                " with given sum";
    else
        cout << "Array doesn't have two"
                " elements with given sum";
 
    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("Array has two elements with given sum");
    else
        printf("Array doesn't have two elements with given sum");
 
    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("Array has two "
                               + "elements with given sum");
        else
            System.out.println("Array doesn't have "
                               + "two elements with given sum");
    }
}


Python




# Python program to check for the sum
# condition to be satisified
 
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 is 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("Array has two elements with the given sum")
else:
    print("Array doesn't have two elements
                                  with the given sum")
 
## This code is contributed by __Devesh Agrawal__


Xem thêm: [Giải Toán 10] Chương 2: Hàm số bậc nhất và bậc hai/ Bài 3: Hàm số bậc hai

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("Array has two elements"
                          + " with given sum");
        else
            Console.Write("Array doesn't have "
                          + "two elements with given sum");
    }
}
 
// This code is contributed by Sam007


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 "Array has two elements " .
                   "with given sum";
else
    echo "Array doesn't have two " .
          "elements with given sum";
     
// This code is contributed by m_kit
?>


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>


Output: 

Array has two elements with the given sum

Complexity Analysis:  

  • Time Complexity: Depends on what sorting algorithm we use. 
    • If Merge Sort or Heap Sort is used then (-)(nlogn) in the worst case.
    • If Quick Sort is used then O(n^2) in the worst case.
  • Auxiliary Space: This too depends on sorting algorithm. The auxiliary space is O(n) for merge sort and O(1) for Heap Sort.

Method 2:

Hashing

.

Approach: 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. Let’s look at the following example. 

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 

Algorithm:  

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

Pseudo Code :  

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]

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 << "Pair with given sum "
                 << sum << " is (" << arr[i] << ","
                    << temp << ")" << endl;
 
        s.insert(arr[i]);
    }
}
 
/* 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
 
// Works only if range elements is limited
#include <stdio.h>
#define MAX 100000
 
void printPairs(int arr[], int arr_size, int sum)
{
    int i, temp;
 
    /*initialize hash set as 0*/
    bool s[MAX] = { 0 };
 
    for (i = 0; i < arr_size; i++)
    {
        temp = sum - arr[i];
        if (s[temp] == 1)
            printf(
                "Pair with given sum %d is (%d, %d) n",
                sum, arr[i], temp);
        s[arr[i]] = 1;
    }
}
 
/* Driver Code */
int main()
{
    int A[] = { 1, 4, 45, 6, 10, 8 };
    int n = 16;
    int arr_size = sizeof(A) / sizeof(A[0]);
 
    printPairs(A, arr_size, n);
 
    getchar();
    return 0;
}


Xem thêm: 5 App Ứng Dụng Phần Mềm Giải Bài Tập Hóa Học Tốt Nhất

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(
                    "Pair with given sum "
                    + sum + " is (" + arr[i]
                    + ", " + temp + ")");
            }
            s.add(arr[i]);
        }
    }
 
    // 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 wtih given sum
 
# function to check for the given sum
# in the array
def printPairs(arr, arr_size, sum):
     
    # Create an empty hash set
    s = set()
     
    for i in range(0, arr_size):
        temp = sum-arr[i]
        if (temp in s):
            print "Pair with given sum "+ str(sum) +
       " is (" + str(arr[i]) + ", " + str(temp) + ")"
        s.add(arr[i])
 
# driver code
A = [1, 4, 45, 6, 10, 8]
n = 16
printPairs(A, len(A), n)
 
# This code is contributed by __Devesh Agrawal__


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("Pair with given sum " +
           sum + " is (" + arr[i] + ", " + temp + ")");
            }
            s.Add(arr[i]);
        }
    }
 
    // 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: 

Pair with given sum 16 is (10, 6)

Complexity Analysis:  

  • 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: If the range of numbers includes negative numbers then also it will work fine.

Method 3: Using remainders of the elements less than x. 

Approach: 
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”. 

Algorithm:  

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]>1 and rem[x-x/2]>1 , then print “Yes” else, print”No”;

Implementation of the above algorithm: 

Xem thêm: How To Use iCloud: What Is It, And What Does It Do?-Macworld UK

C++




// Code in cpp to tell if there
// exists a pair in array whose
// sum results in x.
#include <iostream>
using namespace std;
 
// Funtion to print pairs
void printPairs(int a[], int n, int x)
{
      int i;
    int rem[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.
            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 (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".
                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 article is contributed by Sai Sanjana Gudla


Java




// Code in Java to tell if there
// exists a pair in array whose
// sum results in x.
import java.util.*;
class GFG{
 
// Funtion 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.
      System.out.print("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".
        System.out.print("Yes"
                         + "n");
      }
      else
      {
        System.out.print("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)
      {
        System.out.print("Yes"
                         + "n");
      }
      else
      {
        System.out.print("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 aashish1995


Python3




# Code in Python3 to tell if there
# exists a pair in array whose
# sum results in x.
 
# Funtion 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
{
   
// Funtion 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.
 
// Funtion 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)
Auxiliary Space: O(x)
Related Problems:  

  • Given two unsorted arrays, find all pairs whose sum is x

  • Count pairs with given sum

  • Count all distinct pairs with difference equal to k

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the

DSA Self Paced Course

at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer

Complete Interview Preparation Course

.

In case you wish to attend live classes with industry experts, please refer

Geeks Classes Live

 

My Personal Notes arrow_drop_up

Chuyên mục: Kiến thức

Related Articles

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Check Also
Close
Back to top button