VOOZH about

URL: https://www.geeksforgeeks.org/dsa/given-two-unsorted-arrays-find-pairs-whose-sum-x/

⇱ Find all pairs with a given sum in two unsorted arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find all pairs with a given sum in two unsorted arrays

Last Updated : 23 Jul, 2025

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 3

Input: arr1[] = {1, 2, 4, 5, 7}, arr2[] = {5, 6, 3, 4, 8}, x = 9
Output: 1 8 4 5 5 4

[Naive Approach] Using Two Nested Loops - O(n2) time and O(1) auxiliary space

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:


Output
1 7
7 1
5 3
4 4

Time Complexity :O(n^2) 
Auxiliary Space : O(1)

[Optimized Approach] Using Sorting and Binary Search - O(n log(n) + m log(n)) time and O(1) auxiliary space

Sort one of the arrays and use binary search to find the complement of each element in the second array.

Code Implementation:


Output
1 7
4 4
5 3
7 1

Time Complexity: O(n log(n) + m log(n))
Auxiliary Space: O(1)

[Expected Approach] Using Hashing Approach - O(n + m) time and O(n + m) auxiliary space

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:


Output
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.


Comment
Article Tags: