Given two arrays of integers where maximum size of first array is big and that of second array is small. Your task is to find if there is a pair in the first array whose sum is present in the second array.
Examples:
Input:
4
1 5 10 8
3
2 20 13
Output: 1
Approach: We have x + y = z. This can be rewritten as x = z – y. This means we need to find an element x in array 1 such that it is the result of z(second array) – y(first array). For this, use hashing to keep track of such element x.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool pairExists(int arr1[], int m, int arr2[], int n)
{
unordered_set<int> s;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (s.find(arr2[j] - arr1[i]) != s.end())
return true;
}
s.insert(arr1[i]);
}
return false;
}
int main()
{
int arr1[] = { 1, 5, 10, 8 };
int arr2[] = { 2, 20, 13 };
if (pairExists(arr1, 4, arr2, 3))
cout << 1 << endl;
else
cout << 0 << endl;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static boolean pairExists(int []arr1, int m, int []arr2, int n)
{
Set<Integer> s =new HashSet<Integer>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
{
if (s.contains(arr2[j] - arr1[i]))
return true;
}
s.add(arr1[i]);
}
return false;
}
public static void main(String []args)
{
int []arr1 = { 1, 5, 10, 8 };
int []arr2 = { 2, 20, 13 };
if (pairExists(arr1, 4, arr2, 3))
System.out.println(1);
else
System.out.println(0);
}
}
|
Python3
from typing import List
def pairExists(arr1: List[int], m: int,
arr2: List[int], n: int) -> bool:
s = set()
for i in range(m):
for j in range(n):
if (arr2[2] - arr1[2]) not in s:
return True
s.add(arr1[i])
return False
if __name__ == "__main__":
arr1 = [ 1, 5, 10, 8 ]
arr2 = [ 2, 20, 13 ]
if (pairExists(arr1, 4, arr2, 3)):
print(1)
else:
print(0)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static bool pairExists(int []arr1,
int m, int []arr2, int n)
{
HashSet<int> s = new HashSet<int>();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (s.Contains(arr2[j] - arr1[i]))
return true;
}
s.Add(arr1[i]);
}
return false;
}
public static void Main()
{
int []arr1 = { 1, 5, 10, 8 };
int []arr2 = { 2, 20, 13 };
if (pairExists(arr1, 4, arr2, 3))
Console.WriteLine(1);
else
Console.WriteLine(0);
}
}
|
Javascript
<script>
function pairExists(arr1, m, arr2, n) {
let s = new Set();
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (s.has(arr2[j] - arr1[i]))
return true;
}
s.add(arr1[i]);
}
return false;
}
let arr1 = [1, 5, 10, 8];
let arr2 = [2, 20, 13];
if (pairExists(arr1, 4, arr2, 3))
document.write(1 + "<br>");
else
document.write(0 + "<br>");
</script>
|
Time Complexity: O(m*n)
Auxiliary Space: O(m)