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

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}
Sum of elements in A[] = 11
Sum of elements in B[] = 15
To get same sum from both arrays, we
can swap following values:
1 from A[] and 3 from B[]

Input: A[] = {5, 7, 4, 6}, B[] = {1, 2, 3, 8}
Output: 6 2

Method 1 (Naive Implementation):
Iterate through the arrays and check all pairs of values. Compare new sums or look for a pair with that difference.

C/C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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
?>

chevron_right



Output :

1 3

Time Complexity :- O(n*m)

 
Method 2 -> Other Naive implementation

We are looking for two values, a and b, such that: 
sumA - a + b = sumB - b + a
    2a - 2b  = sumA - sumB
      a - b  = (sumA - sumB) / 2

Therefore, we’re looking for two values that have a specific target difference: (sumA – sumB) / 2.

C/C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP code for naive implementation
#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;
}
  
// Function to calculate : 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);
}
  
void findSwapValues(int A[], int n, int B[], int m)
{
    int target = getTarget(A, n, B, m);
    if (target == 0)
        return;
  
    // Look for val1 and val2, such that
    // val1 - val2 = (sumA - sumB) / 2
    int val1, val2;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (A[i] - B[j] == target) {
                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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 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)
    {
        int target = getTarget(A, n, B, m);
        if (target == 0)
            return;
   
        // Look for val1 and val2, such that
        // val1 - val2 = (sumA - sumB) / 2
        int val1 = 0, val2 = 0;
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < m; j++) 
            {
                if (A[i] - B[j] == target) 
                {
                    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

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python Code for naive implementation
  
# Function to calculate sum of elements of list
def getSum(X):
    sum=0
    for i in X:
        sum+=i
    return sum
  
# Function to calculate : a-b = (sumA - sumB) / 2
def getTarget(A,B):
  
    #Calculations of sums from both lists
    sum1=getSum(A)
    sum2=getSum(B)
  
    # Because the target must be an integer
    if( (sum1-sum2)%2!=0):
        return 0
    return (sum1-sum2)/2
  
  
def findSwapValues(A,B):
    target=getTarget(A,B)
    if target==0:
        return
  
    # Boolean variable used to reduce further iterations
    # after the pair is found
    flag=False
  
    # Look for val1 and val2, such that
    # val1 - val2 = (sumA -sumB) /2
    val1,val2=0,0
    for i in A:
        for j in B:
              
            if i-j == target:
                val1=i
                val2=j
                # Set to True when pair is found
                flag=True
                break
        if flag==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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 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)
    {
        int target = getTarget(A, n, B, m);
        if (target == 0)
            return;
    
        // Look for val1 and val2, such that
        // val1 - val2 = (sumA - sumB) / 2
        int val1 = 0, val2 = 0;
        for (int i = 0; i < n; i++) 
        {
            for (int j = 0; j < m; j++) 
            {
                if (A[i] - B[j] == target) 
                {
                    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 29AjayKumar*/

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP code for naive implementation
  
// 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 to calculate :
// a - b = (sumA - sumB) / 2
function getTarget($A, $n, $B, $m)
{
    // Calculation of sums from
    // both arrays
    $sum1 = getSum($A, $n);
    $sum2 = getSum($B, $m);
  
    // because that the target
    // must be an integer
    if (($sum1 - $sum2) % 2 != 0)
        return 0;
    return (($sum1 - $sum2) / 2);
}
  
function findSwapValues($A, $n, $B, $m)
{
    $target = getTarget($A, $n, $B, $m);
    if ($target == 0)
        return;
  
    // Look for val1 and val2, such that
    // val1 - val2 = (sumA - sumB) / 2
    for ($i = 0; $i < $n; $i++) 
    {
        for ($j = 0; $j < $m; $j++) 
        {
            if ($A[$i] - $B[$j] == $target)
            {
                $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 cotnributed 
// by Akanksha Rai
?>

chevron_right



Output:

1 3

Time Complexity :- O(n*m)

 
Method 3 -> Optimized Solution :-

  • Sort the arrays.
  • Traverse both array simultaneously and do following for every pair.
    1. If the difference is too small then, make it bigger by moving ‘a’ to a bigger value.
    2. If it is too big then, make it smaller by moving b to a bigger value.
    3. If it’s just right, return this pair.

Below image is a dry run of the above approach:

Below is the implementation of the above approach:

C/C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 contibuted by sachin bisht

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right



Output:

2 3

Time Complexity :-
If arrays are sorted : O(n + m)
If arrays aren’t sorted : O(nlog(n) + mlog(m))

 

Method 4 (Hashing)
We can solve this problem in O(m+n) time and O(m) auxiliary space. Below are algorithmic steps.

// assume array1 is small i.e. (m < n)
// where m is array1.length and n is array2.length
1. Find sum1(sum of small array elements) ans sum2
  (sum of larger array elements). // time O(m+n)
2. Make a hashset for small array(here array1).
3. Calculate diff as (sum1-sum2)/2.
4. Run a loop for array2
     for (int i equal to 0 to n-1)
       if (hashset contains (array2[i]+diff))
           print array2[i]+diff and array2[i]
           set flag  and break;
5. If flag is unset then there is no such kind of 
pair.

Thanks to nicky khan for suggesting method 4.

This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks (We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up