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
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++
#include <bits/stdc++.h>
using namespace std;
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;
}
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;
}
|
C
#include <stdio.h>
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;
}
|
Java
import java.io.*;
class GFG {
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" );
}
}
}
|
Python3
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" )
|
C#
using System;
class GFG {
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" );
}
}
}
|
Javascript
<script>
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);
}
</script>
|
Go
package main
import ( "fmt" )
func twoSum(nums [ 5 ]int, target int) {
var flag bool = false
result:=make([]int, 2 )
for i:= 0 ;i<len(nums)- 1 ;i++{
for j:=i+ 1 ;j<len(nums);j++{
if nums[i]+nums[j]==target{
result[ 0 ]=nums[i]
result[ 1 ]=nums[j]
flag = true;
}
}
}
if (flag == false){
fmt.Println( "No" )
} else {
fmt.Printf( "Yes" )
}
}
func main() {
arr2 := [ 5 ]int{ 0 , - 1 , 2 , - 3 , 1 }
var x int = - 2
twoSum(arr2, x)
}
|
Time Complexity: O(N2), Finding pair for every element in the array of size N.
Auxiliary Space: O(1)
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++
#include <bits/stdc++.h>
using namespace std;
bool hasArrayTwoCandidates( int A[], int arr_size, int sum)
{
int l, r;
sort(A, A + arr_size);
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
r--;
}
return 0;
}
int main()
{
int A[] = { 1, 4, 45, 6, 10, -8 };
int n = 16;
int arr_size = sizeof (A) / sizeof (A[0]);
if (hasArrayTwoCandidates(A, arr_size, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
C
#include <stdio.h>
#define bool int
void quickSort( int *, int , int );
bool hasArrayTwoCandidates( int A[], int arr_size, int sum)
{
int l, r;
quickSort(A, 0, arr_size - 1);
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
r--;
}
return 0;
}
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);
}
void quickSort( int A[], int si, int ei)
{
int pi;
if (si < ei) {
pi = partition(A, si, ei);
quickSort(A, si, pi - 1);
quickSort(A, pi + 1, ei);
}
}
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
import java.util.*;
class GFG {
static boolean
hasArrayTwoCandidates( int A[], int arr_size, int sum)
{
int l, r;
Arrays.sort(A);
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
r--;
}
return false ;
}
public static void main(String args[])
{
int A[] = { 1 , 4 , 45 , 6 , 10 , - 8 };
int n = 16 ;
int arr_size = A.length;
if (hasArrayTwoCandidates(A, arr_size, n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python
def hasArrayTwoCandidates(A, arr_size, sum ):
quickSort(A, 0 , arr_size - 1 )
l = 0
r = arr_size - 1
while l < r:
if (A[l] + A[r] = = sum ):
return 1
elif (A[l] + A[r] < sum ):
l + = 1
else :
r - = 1
return 0
def quickSort(A, si, ei):
if si < ei:
pi = partition(A, si, ei)
quickSort(A, si, pi - 1 )
quickSort(A, pi + 1 , ei)
def partition(A, si, ei):
x = A[ei]
i = (si - 1 )
for j in range (si, ei):
if A[j] < = x:
i + = 1
A[i], A[j] = A[j], A[i]
A[i + 1 ], A[ei] = A[ei], A[i + 1 ]
return i + 1
A = [ 1 , 4 , 45 , 6 , 10 , - 8 ]
n = 16
if (hasArrayTwoCandidates(A, len (A), n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool hasArrayTwoCandidates( int [] A, int arr_size,
int sum)
{
int l, r;
sort(A, 0, arr_size - 1);
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
r--;
}
return false ;
}
static int partition( int [] arr, int low, int high)
{
int pivot = arr[high];
int i = (low - 1);
for ( int j = low; j <= high - 1; j++) {
if (arr[j] <= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp1 = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp1;
return i + 1;
}
static void sort( int [] arr, int low, int high)
{
if (low < high) {
int pi = partition(arr, low, high);
sort(arr, low, pi - 1);
sort(arr, pi + 1, high);
}
}
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" );
}
}
|
Javascript
<script>
function hasArrayTwoCandidates(A, arr_size, sum)
{
var l, r;
A.sort();
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
r--;
}
return 0;
}
var A = [ 1, 4, 45, 6, 10, -8 ]
var n = 16;
var arr_size = A.length;
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
function hasArrayTwoCandidates( $A , $arr_size ,
$sum )
{
$l ; $r ;
sort( $A );
$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
$r --;
}
return 0;
}
$A = array (1, 4, 45, 6, 10, -8);
$n = 16;
$arr_size = sizeof( $A );
if (hasArrayTwoCandidates( $A , $arr_size , $n ))
echo "Yes" ;
else
echo "No" ;
?>
|
Go
package main
import (
"fmt"
"sort"
)
func hasArrayTwoCandidates(A []int, arr_size int, sum int) bool {
var l, r int
sort.Ints(A)
l = 0
r = arr_size - 1
for l < r {
if A[l]+A[r] == sum {
return true
} else if A[l]+A[r] < sum {
l++
} else {
r--
}
}
return false
}
func main() {
A := []int{ 1 , 4 , 45 , 6 , 10 , - 8 }
n := 16
arr_size := len(A)
if hasArrayTwoCandidates(A, arr_size, n) {
fmt.Println( "Yes" )
} else {
fmt.Println( "No" )
}
}
|
Time Complexity: O(NlogN), Time complexity for sorting the array
Auxiliary Space: O(1)
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 False
Below is the implementation of the above approach:
C++
#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;
if (A[m] == searchKey)
return true ;
if (A[m] < searchKey)
low = m + 1;
else
high = m - 1;
}
return false ;
}
bool checkTwoSum( int A[], int arr_size, int sum)
{
int l, r;
sort(A, A + arr_size);
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 ;
}
int main()
{
int A[] = { 1, 4, 45, 6, 10, -8 };
int n = 14;
int arr_size = sizeof (A) / sizeof (A[0]);
if (checkTwoSum(A, arr_size, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
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 ;
if (A[m] == searchKey)
return true ;
if (A[m] < searchKey)
low = m + 1 ;
else
high = m - 1 ;
}
return false ;
}
static boolean checkTwoSum( int A[], int arr_size,
int sum)
{
int l, r;
Arrays.sort(A);
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 ;
}
public static void main(String args[])
{
int A[] = { 1 , 4 , 45 , 6 , 10 , - 8 };
int n = 14 ;
int arr_size = A.length;
if (checkTwoSum(A, arr_size, n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python
def binarySearch(A, low, high, searchKey):
m = 0
while (low < = high):
m = (high + low) / / 2
if (A[m] = = searchKey):
return 1
if (A[m] < searchKey):
low = m + 1
else :
high = m - 1
return 0
def checkTwoSum(A, arr_size, sum ):
A.sort()
l = 0
r = arr_size - 1
i = 0
while i < arr_size - 1 :
searchKey = sum - A[i]
if (binarySearch(A, i + 1 , r, searchKey) = = 1 ):
return 1
i = i + 1
return 0
A = [ 1 , 4 , 45 , 6 , 10 , - 8 ]
n = 14
if (checkTwoSum(A, len (A), n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
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;
if (A[m] == searchKey)
return true ;
if (A[m] < searchKey)
low = m + 1;
else
high = m - 1;
}
return false ;
}
static bool checkTwoSum( int [] A, int arr_size, int sum)
{
Array.Sort(A);
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 ;
}
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" );
}
}
|
Javascript
function binarySearch( A, low, high, searchKey)
{
while (low <= high) {
let m = low + (high - low) / 2;
if (A[m] == searchKey)
return true ;
if (A[m] < searchKey)
low = m + 1;
else
high = m - 1;
}
return false ;
}
function checkTwoSum( A, arr_size, sum)
{
A.sort();
for (let i = 0; i < arr_size - 1; i++) {
let searchKey = sum - A[i];
if (binarySearch(A, i + 1, arr_size - 1, searchKey) == true ) {
return true ;
}
}
return false ;
}
let A = [ 1, 4, 45, 6, 10, -8 ];
let n = 14;
let arr_size = 6;
if (checkTwoSum(A, arr_size, n))
console.log( "Yes" );
else
console.log( "No" );
|
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++
#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;
}
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);
return 0;
}
|
C
#include <stdio.h>
#define MAX 100000
void printPairs( int arr[], int arr_size, int target)
{
int i, temp;
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" );
}
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
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];
if (s.contains(temp)) {
System.out.println( "Yes" );
return ;
}
s.add(arr[i]);
}
System.out.println( "No" );
}
public static void main(String[] args)
{
int A[] = { 1 , 4 , 45 , 6 , 10 , 8 };
int n = 16 ;
printpairs(A, n);
}
}
|
Python3
def printPairs(arr, arr_size, sum ):
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" )
A = [ 1 , 4 , 45 , 6 , 10 , 8 ]
n = 16
printPairs(A, len (A), n)
|
C#
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];
if (s.Contains(temp)) {
Console.Write( "Yes" );
return ;
}
s.Add(arr[i]);
}
Console.Write( "No" );
}
static void Main()
{
int [] A = new int [] { 1, 4, 45, 6, 10, 8 };
int n = 16;
printpairs(A, n);
}
}
|
Javascript
<script>
function printpairs(arr, sum)
{
let s = new Set();
for (let i = 0; i < arr.length; ++i)
{
let temp = sum - arr[i];
if (s.has(temp)) {
document.write(
"Pair with given sum "
+ sum + " is (" + arr[i]
+ ", " + temp + ")" );
}
s.add(arr[i]);
}
}
let A = [ 1, 4, 45, 6, 10, 8 ];
let n = 16;
printpairs(A, n);
</script>
|
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++
#include <iostream>
using namespace std;
void printPairs( int a[], int n, int x)
{
int i;
int rem[x];
for (i = 0; i < x; i++)
rem[i] = 0;
for (i = 0; i < n; i++)
if (a[i] < x)
rem[a[i] % x]++;
for (i = 1; i < x / 2; i++) {
if (rem[i] > 0 && rem[x - i] > 0) {
cout << "Yes\n" ;
break ;
}
}
if (i >= x / 2) {
if (x % 2 == 0) {
if (rem[x / 2] > 1)
cout << "Yes\n" ;
else
cout << "No\n" ;
}
else {
if (rem[x / 2] > 0 && rem[x - x / 2] > 0)
cout << "Yes\n" ;
else
cout << "No\n" ;
}
}
}
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);
return 0;
}
|
C
#include <stdio.h>
void printPairs( int a[], int n, int x)
{
int i;
int rem[x];
for (i = 0; i < x; i++)
rem[i] = 0;
for (i = 0; i < n; i++)
if (a[i] < x)
rem[a[i] % x]++;
for (i = 1; i < x / 2; i++) {
if (rem[i] > 0 && rem[x - i] > 0) {
printf ( "Yes\n" );
break ;
}
}
if (i >= x / 2) {
if (x % 2 == 0) {
if (rem[x / 2] > 1)
printf ( "Yes\n" );
else
printf ( "No\n" );
}
else {
if (rem[x / 2] > 0 && rem[x - x / 2] > 0)
printf ( "Yes\n" );
else
printf ( "No\n" );
}
}
}
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);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void printPairs( int a[], int n, int x)
{
int i;
int [] rem = new int [x];
for (i = 0 ; i < x; i++)
rem[i] = 0 ;
for (i = 0 ; i < n; i++)
if (a[i] < x)
rem[a[i] % x]++;
for (i = 1 ; i < x / 2 ; i++) {
if (rem[i] > 0 && rem[x - i] > 0 ) {
System.out.println( "Yes" );
break ;
}
}
if (i >= x / 2 ) {
if (x % 2 == 0 ) {
if (rem[x / 2 ] > 1 )
System.out.println( "Yes" );
else
System.out.println( "No" );
}
else {
if (rem[x / 2 ] > 0 && rem[x - x / 2 ] > 0 )
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
}
public static void main(String[] args)
{
int A[] = { 1 , 4 , 45 , 6 , 10 , 8 };
int n = 16 ;
int arr_size = A.length;
printPairs(A, arr_size, n);
}
}
|
Python3
def printPairs(a, n, x):
rem = []
for i in range (x):
rem.append( 0 )
for i in range (n):
if (a[i] < x):
rem[a[i] % x] + = 1
for i in range ( 1 , x / / 2 ):
if (rem[i] > 0 and rem[x - i] > 0 ):
print ( "Yes" )
break
if (i > = x / / 2 ):
if (x % 2 = = 0 ):
if (rem[x / / 2 ] > 1 ):
print ( "Yes" )
else :
print ( "No" )
else :
if (rem[x / / 2 ] > 0 and
rem[x - x / / 2 ] > 0 ):
print ( "Yes" )
else :
print ( "No" )
A = [ 1 , 4 , 45 , 6 , 10 , 8 ]
n = 16
arr_size = len (A)
printPairs(A, arr_size, n)
|
C#
using System;
class GFG {
static void printPairs( int [] a, int n, int x)
{
int i;
int [] rem = new int [x];
for (i = 0; i < x; i++) {
rem[i] = 0;
}
for (i = 0; i < n; i++) {
if (a[i] < x) {
rem[a[i] % x]++;
}
}
for (i = 1; i < x / 2; i++) {
if (rem[i] > 0 && rem[x - i] > 0) {
Console.Write( "Yes"
+ "\n" );
break ;
}
}
if (i >= x / 2) {
if (x % 2 == 0) {
if (rem[x / 2] > 1) {
Console.Write( "Yes"
+ "\n" );
}
else {
Console.Write( "No"
+ "\n" );
}
}
else {
if (rem[x / 2] > 0 && rem[x - x / 2] > 0) {
Console.Write( "Yes"
+ "\n" );
}
else {
Console.WriteLine( "No"
+ "\n" );
}
}
}
}
public static void Main( string [] args)
{
int [] A = { 1, 4, 45, 6, 10, 8 };
int n = 16;
int arr_size = A.Length;
printPairs(A, arr_size, n);
}
}
|
Javascript
<script>
function printPairs(a, n, x)
{
let i;
let rem = new Array(x);
for (i = 0; i < x; i++)
{
rem[i] = 0;
}
for (i = 0; i < n; i++)
{
if (a[i] < x)
{
rem[a[i] % x]++;
}
}
for (i = 1; i < x / 2; i++)
{
if (rem[i] > 0 && rem[x - i] > 0)
{
document.write( "Yes" + "</br>" );
break ;
}
}
if (i >= x / 2)
{
if (x % 2 == 0)
{
if (rem[x / 2] > 1)
{
document.write( "Yes" + "</br>" );
}
else
{
document.write( "No" + "</br>" );
}
}
else
{
if (rem[x / 2] > 0 &&
rem[x - x / 2] > 0)
{
document.write( "Yes" + "</br>" );
}
else
{
document.write( "No" + "</br>" );
}
}
}
}
let A = [ 1, 4, 45, 6, 10, 8 ];
let n = 16;
let arr_size = A.length;
printPairs(A, arr_size, n);
</script>
|
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
14 Aug, 2023
Like Article
Save Article