Open In App

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

Last Updated : 05 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

C++
// CPP code naive solution to find a pair swapping 
// which makes sum of arrays sum. 
#include <iostream> 
using namespace std; 

// Function to calculate sum of elements of array 
int getSum(int X[], int n) 
{ 
    int sum = 0; 
    for (int i = 0; i < n; i++) 
        sum += X[i]; 
    return sum; 
} 

void findSwapValues(int A[], int n, int B[], int m) 
{ 
    // Calculation of sums from both arrays 
    int sum1 = getSum(A, n); 
    int sum2 = getSum(B, m); 

    // Look for val1 and val2, such that 
    // sumA - val1 + val2 = sumB - val2 + val1 
    int newsum1, newsum2, val1, val2; 
    for (int i = 0; i < n; i++) { 
        for (int j = 0; j < m; j++) { 
            newsum1 = sum1 - A[i] + B[j]; 
            newsum2 = sum2 - B[j] + A[i]; 
            if (newsum1 == newsum2) { 
                val1 = A[i]; 
                val2 = B[j]; 
            } 
        } 
    } 

    cout << val1 << " " << val2; 
} 

// Driver code 
int main() 
{ 
    int A[] = { 4, 1, 2, 1, 1, 2 }; 
    int n = sizeof(A) / sizeof(A[0]); 
    int B[] = { 3, 6, 3, 3 }; 
    int m = sizeof(B) / sizeof(B[0]); 

    // Call to function 
    findSwapValues(A, n, B, m); 
    return 0; 
} 
Java
// Java program to find a pair swapping
// which makes sum of arrays sum
import java.io.*;

class GFG 
{
    // Function to calculate sum of elements of array
    static int getSum(int X[], int n)
    {
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += X[i];
        return sum;
    }
    
    // Function to prints elements to be swapped
    static void findSwapValues(int A[], int n, int B[], int m)
    {
        // Calculation of sums from both arrays
        int sum1 = getSum(A, n);
        int sum2 = getSum(B, m);
 
        // Look for val1 and val2, such that
        // sumA - val1 + val2 = sumB - val2 + val1
        int newsum1, newsum2, val1 = 0, val2 = 0;
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < m; j++) 
            {
                newsum1 = sum1 - A[i] + B[j];
                newsum2 = sum2 - B[j] + A[i];
                if (newsum1 == newsum2) 
                {
                    val1 = A[i];
                    val2 = B[j];
                }
            }
        }
 
        System.out.println(val1+" "+val2);
    }
    
    // driver program
    public static void main (String[] args) 
    {
        int A[] = { 4, 1, 2, 1, 1, 2 };
        int n = A.length;
        int B[] = { 3, 6, 3, 3 };
        int m = B.length;
 
        // Call to function
        findSwapValues(A, n, B, m);
    }
}

// Contributed by Pramod Kumar 
Python
# Python code naive solution to find a pair swapping
# which makes sum of lists sum.

# Function to calculate sum of elements of list
def getSum(X):
    sum=0
    for i in X:
        sum+=i
    return sum

# Function to prints elements to be swapped
def findSwapValues(A,B):
    # Calculation if sums from both lists
    sum1=getSum(A)
    sum2=getSum(B)

    # Boolean variable used to reduce further iterations
    # after the pair is found
    k=False

    # Lool for val1 and val2, such that
    # sumA - val1 + val2 = sumB -val2 + val1
    val1,val2=0,0
    for i in A:
        for j in B:
            newsum1=sum1-i+j
            newsum2=sum2-j+i
            
            if newsum1 ==newsum2:
                val1=i
                val2=j
                # Set to True when pair is found
                k=True
                break
        # If k is True, it means pair is found.
        # So, no further iterations.
        if k==True:
            break
    print (val1,val2)
    return


# Driver code
A=[4,1,2,1,1,2]
B=[3,6,3,3]

# Call to function
findSwapValues(A,B)

# code contributed by sachin bisht
C#
// C# program to find a pair swapping
// which makes sum of arrays sum
using System; 

class GFG 
{
// Function to calculate sum 
// of elements of array
static int getSum(int[] X, int n)
{
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += X[i];
    return sum;
}

// Function to prints elements 
// to be swapped
static void findSwapValues(int[] A, int n, 
                           int[] B, int m)
{
    // Calculation of sums from
    // both arrays
    int sum1 = getSum(A, n);
    int sum2 = getSum(B, m);

    // Look for val1 and val2, such that
    // sumA - val1 + val2 = sumB - val2 + val1
    int newsum1, newsum2,   
        val1 = 0, val2 = 0;
    for (int i = 0; i < n; i++) 
    {
        for (int j = 0; j < m; j++) 
        {
            newsum1 = sum1 - A[i] + B[j];
            newsum2 = sum2 - B[j] + A[i];
            if (newsum1 == newsum2) 
            {
                val1 = A[i];
                val2 = B[j];
            }
        }
    }

    Console.Write(val1 + " " + val2);
}

// Driver Code
public static void Main () 
{
    int[] A = { 4, 1, 2, 1, 1, 2 };
    int n = A.Length;
    int[] B = { 3, 6, 3, 3 };
    int m = B.Length;

    // Call to function
    findSwapValues(A, n, B, m);
}
}

// This code is contributed 
// by ChitraNayal
Javascript
<script>
// Javascript program to find a pair swapping
// which makes sum of arrays sum
    
    // Function to calculate sum of elements of array
    function  getSum(X,n)
    {
        let sum = 0;
        for (let i = 0; i < n; i++)
            sum += X[i];
        return sum;
    }
    
    // Function to prints elements to be swapped
    function findSwapValues(A,n,B,m)
    {
        // Calculation of sums from both arrays
        let sum1 = getSum(A, n);
        let sum2 = getSum(B, m);
   
        // Look for val1 and val2, such that
        // sumA - val1 + val2 = sumB - val2 + val1
        let newsum1, newsum2, val1 = 0, val2 = 0;
        for (let i = 0; i < n; i++) 
        {
            for (let j = 0; j < m; j++) 
            {
                newsum1 = sum1 - A[i] + B[j];
                newsum2 = sum2 - B[j] + A[i];
                if (newsum1 == newsum2) 
                {
                    val1 = A[i];
                    val2 = B[j];
                }
            }
        }
   
        document.write(val1+" "+val2);
    }
    
    // driver program
    let A=[4, 1, 2, 1, 1, 2];
    let n = A.length;
    let B=[3, 6, 3, 3 ];
    let m = B.length;
    // Call to function
    findSwapValues(A, n, B, m);
    
    //This code is contributed by avanitrachhadiya2155
    
</script>
PHP
<?php
// PHP code naive solution to find 
// a pair swapping which makes sum
// of arrays sum.

// Function to calculate sum of
// elements of array
function getSum($X, $n)
{
    $sum = 0;
    for ($i = 0; $i < $n; $i++)
        $sum += $X[$i];
    return $sum;
}

function findSwapValues($A, $n, $B, $m)
{
    // Calculation of sums from both arrays
    $sum1 = getSum($A, $n);
    $sum2 = getSum($B, $m);

    // Look for val1 and val2, such that
    // sumA - val1 + val2 = sumB - val2 + val1
    for ($i = 0; $i < $n; $i++) 
    {
        for ($j = 0; $j < $m; $j++)
        {
            $newsum1 = $sum1 - $A[$i] + $B[$j];
            $newsum2 = $sum2 - $B[$j] + $A[$i];
            if ($newsum1 == $newsum2)
            {
                $val1 = $A[$i];
                $val2 = $B[$j];
            }
        }
    }

    echo $val1 . " " . $val2;
}

// Driver code
$A = array(4, 1, 2, 1, 1, 2 );
$n = sizeof($A);
$B = array(3, 6, 3, 3 );
$m = sizeof($B);

// Call to function
findSwapValues($A, $n, $B, $m);

// This code is contributed 
// by Akanksha Rai
?>

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: 

C++
// CPP code for optimized implementation 
#include <bits/stdc++.h> 
using namespace std; 

// Returns sum of elements in X[] 
int getSum(int X[], int n) 
{ 
    int sum = 0; 
    for (int i = 0; i < n; i++) 
        sum += X[i]; 
    return sum; 
} 

// Finds value of 
// a - b = (sumA - sumB) / 2 
int getTarget(int A[], int n, int B[], int m) 
{ 
    // Calculation of sums from both arrays 
    int sum1 = getSum(A, n); 
    int sum2 = getSum(B, m); 

    // because that the target must be an integer 
    if ((sum1 - sum2) % 2 != 0) 
        return 0; 
    return ((sum1 - sum2) / 2); 
} 

// Prints elements to be swapped 
void findSwapValues(int A[], int n, int B[], int m) 
{ 
    // Call for sorting the arrays 
    sort(A, A + n); 
    sort(B, B + m); 

    // Note that target can be negative 
    int target = getTarget(A, n, B, m); 

    // target 0 means, answer is not possible 
    if (target == 0) 
        return; 

    int i = 0, j = 0; 
    while (i < n && j < m) { 
        int diff = A[i] - B[j]; 
        if (diff == target) { 
            cout << A[i] << " " << B[j]; 
            return; 
        } 

        // Look for a greater value in A[] 
        else if (diff < target) 
            i++; 

        // Look for a greater value in B[] 
        else
            j++; 
    } 
} 

// Driver code 
int main() 
{ 
    int A[] = { 4, 1, 2, 1, 1, 2 }; 
    int n = sizeof(A) / sizeof(A[0]); 

    int B[] = { 1, 6, 3, 3 }; 
    int m = sizeof(B) / sizeof(B[0]); 

    findSwapValues(A, n, B, m); 
    return 0; 
} 
Java
// Java code for optimized implementation
import java.io.*;
import java.util.*;

class GFG 
{
    // Function to calculate sum of elements of array
    static int getSum(int X[], int n)
    {
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += X[i];
        return sum;
    }
    
    // Function to calculate : a - b = (sumA - sumB) / 2
    static int getTarget(int A[], int n, int B[], int m)
    {
        // Calculation of sums from both arrays
        int sum1 = getSum(A, n);
        int sum2 = getSum(B, m);
 
        // because that the target must be an integer
        if ((sum1 - sum2) % 2 != 0)
            return 0;
        return ((sum1 - sum2) / 2);
    }
    
    // Function to prints elements to be swapped
    static void findSwapValues(int A[], int n, int B[], int m)
    {
        // Call for sorting the arrays
        Arrays.sort(A);
        Arrays.sort(B);
 
        // Note that target can be negative
        int target = getTarget(A, n, B, m);
 
        // target 0 means, answer is not possible
        if (target == 0)
            return;
 
        int i = 0, j = 0;
        while (i < n && j < m) 
        {
            int diff = A[i] - B[j];
            if (diff == target) 
            {
                System.out.println(A[i]+" "+B[i]);
                return;
            }
 
            // Look for a greater value in A[]
            else if (diff < target)
                i++;
 
            // Look for a greater value in B[]
            else
                j++;
        }
    }
    
    // driver program
    public static void main (String[] args) 
    {
        int A[] = { 4, 1, 2, 1, 1, 2 };
        int n = A.length;
        int B[] = { 3, 6, 3, 3 };
        int m = B.length;
 
        // Call to function
        findSwapValues(A, n, B, m);
    }
}

// Contributed by Pramod Kumar
Python
# Python code for optimized implementation

#Returns sum of elements in list
def getSum(X):
    sum=0
    for i in X:
        sum+=i
    return sum

# Finds value of
# a - b = (sumA - sumB) / 2
def getTarget(A,B):
    # Calculations of sumd from both lists
    sum1=getSum(A)
    sum2=getSum(B)

    # Because that target must be an integer
    if( (sum1-sum2)%2!=0):
        return 0
    return (sum1-sum2)//2

# Prints elements to be swapped
def findSwapValues(A,B):
    # Call for sorting the lists
    A.sort()
    B.sort()

    #Note that target can be negative
    target=getTarget(A,B)

    # target 0 means, answer is not possible
    if(target==0):
        return
    i,j=0,0
    while(i<len(A) and j<len(B)):
        diff=A[i]-B[j]
        if diff == target:
            print (A[i],B[j])
            return
        # Look for a greater value in list A
        elif diff <target:
            i+=1
        # Look for a greater value in list B
        else:
            j+=1

A=[4,1,2,1,1,2]
B=[3,6,3,3]

findSwapValues(A,B)

#code contributed by sachin bisht
C#
// C# code for optimized implementation
using System; 

class GFG 
{
    // Function to calculate sum of elements of array
    static int getSum(int []X, int n)
    {
        int sum = 0;
        for (int i = 0; i < n; i++)
            sum += X[i];
        return sum;
    }
    
    // Function to calculate : a - b = (sumA - sumB) / 2
    static int getTarget(int []A, int n, int []B, int m)
    {
        // Calculation of sums from both arrays
        int sum1 = getSum(A, n);
        int sum2 = getSum(B, m);

        // because that the target must be an integer
        if ((sum1 - sum2) % 2 != 0)
            return 0;
        return ((sum1 - sum2) / 2);
    }
    
    // Function to prints elements to be swapped
    static void findSwapValues(int []A, int n, int []B, int m)
    {
        // Call for sorting the arrays
        Array.Sort(A);
        Array.Sort(B);

        // Note that target can be negative
        int target = getTarget(A, n, B, m);

        // target 0 means, answer is not possible
        if (target == 0)
            return;

        int i = 0, j = 0;
        while (i < n && j < m) 
        {
            int diff = A[i] - B[j];
            if (diff == target) 
            {
                Console.WriteLine(A[i]+" "+B[i]);
                return;
            }

            // Look for a greater value in A[]
            else if (diff < target)
                i++;

            // Look for a greater value in B[]
            else
                j++;
        }
    }
    
    // Driver code
    public static void Main (String[] args) 
    {
        int []A = { 4, 1, 2, 1, 1, 2 };
        int n = A.Length;
        int []B = { 3, 6, 3, 3 };
        int m = B.Length;

        // Call to function
        findSwapValues(A, n, B, m);
    }
}

// This code has been contributed by 29AjayKumar
Javascript
<script>
// Javascript code for optimized implementation

// Function to calculate sum of elements of array
function getSum(X,n)
{
    let sum = 0;
        for (let i = 0; i < n; i++)
            sum += X[i];
        return sum;
}

// Function to calculate : a - b = (sumA - sumB) / 2
function getTarget(A,n,B,m)
{
    // Calculation of sums from both arrays
        let sum1 = getSum(A, n);
        let sum2 = getSum(B, m);
  
        // because that the target must be an integer
        if ((sum1 - sum2) % 2 != 0)
            return 0;
        return ((sum1 - sum2) / 2);
}

// Function to prints elements to be swapped
function findSwapValues(A,n,B,m)
{
    // Call for sorting the arrays
        A.sort(function(a,b){return a-b;});
        B.sort(function(a,b){return a-b;});
          
        // Note that target can be negative
        let target = getTarget(A, n, B, m);
          
        // target 0 means, answer is not possible
        if (target == 0)
            return;
  
        let i = 0, j = 0;
        while (i < n && j < m)
        {
            let diff = A[i] - B[j];
            
            if (diff == target)
            {
                document.write(A[i]+" "+B[j]);
                return;
            }
  
            // Look for a greater value in A[]
            else if (diff < target)
                i++;
  
            // Look for a greater value in B[]
            else
                j++;
        }
}

// driver program
let A=[4, 1, 2, 1, 1, 2 ];
let n = A.length;
let B=[3, 6, 3, 3 ];
let m = B.length;
// Call to function
findSwapValues(A, n, B, m);


// This code is contributed by unknown2108
</script>

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:

C++
#include <bits/stdc++.h>
using namespace std;

// function to find the values to swap
void findSwapValues(int A[], int n, int B[], int m)
{
    // Find the sum of both the arrays
    int sumA = accumulate(A, A + n, 0);
    int sumB = accumulate(B, B + m, 0);

    // Check if the difference between the sum of both the
    // arrays is even or not
    if ((sumA - sumB) % 2 != 0) {
        cout << "No Possible Pair exists" << endl;
        return;
    }

    // Unordered set to store all the elements of A
    unordered_set<int> possibleX;
    for (int i = 0; i < n; i++) {
        possibleX.insert(A[i]);
    }

    // Iterate over all the elements of B[] and check if an
    // element with the value = X is present in A[] or not
    for (int i = 0; i < m; i++) {
        int X = (sumA - sumB) / 2 + B[i];
        if (possibleX.find(X) != possibleX.end()) {
            cout << X << " " << B[i] << endl;
            return;
        }
    }

    cout << "No Possible Pair exists" << endl;
}

int main()
{

    // Sample Input
    int A[] = { 4, 1, 2, 1, 1, 2 };
    int n = sizeof(A) / sizeof(A[0]);

    int B[] = { 3, 6, 3, 3 };
    int m = sizeof(B) / sizeof(B[0]);

    // Function call to print a valid pair
    findSwapValues(A, n, B, m);

    return 0;
}
Java
import java.util.*;

class GFG {
    // Function to find the values to swap
    public static void findSwapValues(int[] A, int n,
                                      int[] B, int m)
    {
        // Find the sum of both the arrays
        int sumA = Arrays.stream(A).sum();
        int sumB = Arrays.stream(B).sum();

        // Check if the difference between the sum of both
        // the arrays is even or not
        if ((sumA - sumB) % 2 != 0) {
            System.out.println("No Possible Pair exists");
            return;
        }

        // Set to store all the elements of A
        Set<Integer> possibleX = new HashSet<>();
        for (int i = 0; i < n; i++) {
            possibleX.add(A[i]);
        }

        // Iterate over all the elements of B and check if
        // an element with the value = X is present in A or
        // not
        for (int i = 0; i < m; i++) {
            int X = (sumA - sumB) / 2 + B[i];
            if (possibleX.contains(X)) {
                System.out.println(X + " " + B[i]);
                return;
            }
        }

        System.out.println("No Possible Pair exists");
    }

    public static void main(String[] args)
    {
        // Sample Input
        int[] A = { 4, 1, 2, 1, 1, 2 };
        int n = A.length;

        int[] B = { 3, 6, 3, 3 };
        int m = B.length;

        // Function call to print a valid pair
        findSwapValues(A, n, B, m);
    }
}
Python
def find_swap_values(A, B):
    # Find the sum of both the arrays
    sumA = sum(A)
    sumB = sum(B)

    # Check if the difference between the sum of both the arrays is even or not
    if (sumA - sumB) % 2 != 0:
        print("No Possible Pair exists")
        return

    # Set to store all the elements of A
    possibleX = set(A)

    # Iterate over all the elements of B and check if an
    # element with the value = X is present in A or not
    for Y in B:
        X = (sumA - sumB) // 2 + Y
        if X in possibleX:
            print(X, Y)
            return

    print("No Possible Pair exists")

# Sample Input
A = [4, 1, 2, 1, 1, 2]
B = [3, 6, 3, 3]

# Function call to print a valid pair
find_swap_values(A, B)

Output
1 3

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



Next Article
Article Tags :
Practice Tags :

Similar Reads