VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-a-pair-swapping-which-makes-sum-of-two-arrays-same/

⇱ Find a pair of elements swapping which makes sum of two arrays same - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find a pair of elements swapping which makes sum of two arrays same

Last Updated : 5 Aug, 2024

Given two arrays of integers, find a pair of values (one value from each array) that you can swap to give the two arrays the same sum.

Examples:

Input: A[] = {4, 1, 2, 1, 1, 2}, B[] = (3, 6, 3, 3) 
Output: 1 3 
Explanation: Sum of elements in A[] = 11 and Sum of elements in B[] = 15. To get same sum from both arrays, we can swap 1 from A[] with 3 from B[].

Input: A[] = {5, 7, 4, 6}, B[] = {1, 2, 3, 8} 
Output: 6 2
Explanation: Sum of elements in A[] = 22 and Sum of elements in B[] = 14. To get same sum from both arrays, we can swap 6 from A[] and 2 from B[].

Approaches to find a pair to swap which makes sum of two arrays same:

[Naive Approach] Check all possible pairs - O(N*M) Time and O(1) Space:

Iterate through the arrays and check all pairs of values. For each element in A[], iterate over all the elements of B[], and check if swapping these two elements will make the sum equal. 

Below is the implementation of the above algorithm: 


Output
1 3

Time Complexity :- O(n*m)
Space Complexity : O(1)

[Better Approach] Sorting both the arrays - O(NlogN + MlogM) Time and O(1) Space:

Suppose the sum of array A[] is sumA and sum of array B[] us sumB, then we need to find a value in A[], say X and a value in B[], say Y, such that:

sumA - X + Y = sumB - Y + X
2X - 2Y = sumA - sumB
X - Y = (sumA - sumB) / 2

To find the elements X and Y, we can sort the array and traverse the array simultaneously using two pointers,

  • If the difference of X and Y is too small then, make it bigger by moving X to a bigger value.
  • If the difference of X and Y is too big then, make it smaller by moving Y to a bigger value.
  • If the difference of X and Y is equal to (sumA - sumB)/2, return this pair.

Below is the implementation of the above approach: 


Output
2 3

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

[Expected Approach] Using Hashing - O(N + M) Time and O(N) Space:

As discussed in the previous approach, we need to find an element in A[], say X and an element in B[], say Y such that X - Y = (SumA - SumB)/2, where SumA is the sum of all elements in A[] and SumB is the sum of all elements in B[].

In order to find such a pair, we can use a hash set to store all the values of array A[]. Then, we can iterate on array B[], and for each value in B[] check if ((sumA - sumB)/2 + Y) is present in the hash set or not. If it is present, then print the current element as Y and the element present in the hashset as X.

Below is an implementation of the approach:


Output
1 3

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

Comment
Article Tags: