You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to x.
52
+
53
+
Examples:
54
+
55
+
Input : arr1[] = {-1, -2, 4, -6, 5, 7}
56
+
arr2[] = {6, 3, 4, 0}
57
+
x = 8
58
+
Output : 4 4
59
+
5 3
60
+
61
+
Input : arr1[] = {1, 2, 4, 5, 7}
62
+
arr2[] = {5, 6, 3, 4, 8}
63
+
x = 9
64
+
Output : 1 8
65
+
4 5
66
+
5 4
67
+
Asked in : Amazon
68
+
69
+
Recommended: Please solve it on "PRACTICE " first, before moving on to the solution.
70
+
A Naive approach is to simply run two loops and pick elements from both arrays. One by one check that both elements sum is equal to given value x or not.
71
+
72
+
// C++ program to find all pairs in both arrays
73
+
// whose sum is equal to given value x
74
+
#include<bits/stdc++.h>
75
+
using namespace std;
76
+
77
+
// Function to print all pairs in both arrays
78
+
// whose sum is equal to given value x
79
+
void findPairs(int arr1[], int arr2[], int n,
80
+
int m, int x)
81
+
{
82
+
for (int i=0; i<n; i++)
83
+
for (int j=0; j<m; j++)
84
+
if (arr1[i] + arr2[j] == x)
85
+
cout << arr1[i] << " "
86
+
<< arr2[j] << endl;
87
+
}
88
+
89
+
// Driver code
90
+
int main()
91
+
{
92
+
int arr1[] = {1, 2, 3, 7, 5, 4};
93
+
int arr2[] = {0, 7, 4, 3, 2, 1};
94
+
int n = sizeof(arr1)/sizeof(int);
95
+
int m = sizeof(arr2)/sizeof(int);
96
+
int x = 8;
97
+
findPairs(arr1, arr2, n, m, x);
98
+
return 0;
99
+
}
100
+
Run on IDE
101
+
Output:
102
+
103
+
1 7
104
+
7 1
105
+
5 3
106
+
4 4
107
+
Time Complexity : O(n^2)
108
+
Auxiliary Space : O(1)
109
+
110
+
An Efficient solution of this problem is to hashing. Hash table is implemented using unordered_set in C++. We store all first array elements in hash table. For elements of second array, we subtract every element from x and check the result in hash table. If result is present, we print the element and key in hash (which is an element of first array).
0 commit comments