![]() |
VOOZH | about |
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to a given value X.
Examples:
Input: arr1[] = {-1, -2, 4, -6, 5, 7}, arr2[] = {6, 3, 4, 0} , x = 8
Output: 4 4 5 3Input: arr1[] = {1, 2, 4, 5, 7}, arr2[] = {5, 6, 3, 4, 8}, x = 9
Output: 1 8 4 5 5 4
Table of Content
The very basic idea is to use two nested loops to iterate over each element in arr1 and for each element in arr1, iterate over each element in arr2. Check if the sum of the current elements from arr1 and arr2 equals X. If yes then print the pair.
Code Implementation:
1 7 7 1 5 3 4 4
Time Complexity :O(n^2)
Auxiliary Space : O(1)
Sort one of the arrays and use binary search to find the complement of each element in the second array.
Code Implementation:
1 7 4 4 5 3 7 1
Time Complexity: O(n log(n) + m log(n))
Auxiliary Space: O(1)
The idea is to use a hash set to store elements of one array and for each element in the second array, calculate the required complement that would sum to X and check if this complement exists in the hash set. If such pair is present, we print the pairs.
Code Implementation:
6 2 4 4 6 2 7 1
Time Complexity: O(n + m)
Auxiliary Space: O(n + m)
Please refer 2Sum - Complete Tutorial for all variations of 2SUM problem.