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

Last Updated : 15 Jul, 2026

Given two arrays of integers a[] and b[], the task is to check if a pair of values (one value from each array) exists such that swapping the elements of the pair will make the sum of two arrays equal.

Examples:  

Input: a[] = [4, 1, 2, 1, 1, 2], b[] = [3, 6, 3, 3]
Output: true
Explanation: 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: true
Explanation: We can swap 6 from array a[] and 2 from array b[]

Try It Yourself
redirect icon

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

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
bool findSwapValues(vector<int> &a, vector<int> &b)
{

    // getting sizes of both arrays
    int n = a.size();
    int m = b.size();

    // calculating sum of elements of both arrays
    int sum1 = 0, sum2 = 0;
    for (int i = 0; i < n; i++)
        sum1 += a[i];

    for (int j = 0; j < m; j++)
        sum2 += b[j];

    // variables to store new sums after swapping
    int newsum1, newsum2;

    // traversing each element of first array
    for (int i = 0; i < n; i++)
    {

        // traversing each element of second array
        for (int j = 0; j < m; j++)
        {

            // calculating new sum if a[i] and b[j] are swapped
            newsum1 = sum1 - a[i] + b[j];
            newsum2 = sum2 - b[j] + a[i];

            // checking if both sums become equal
            if (newsum1 == newsum2)
            {
                return true; // valid pair found
            }
        }
    }

    // if no such pair exists
    return false;
}
// Driver code
int main() {
    
    // initializing first array
    vector<int> a = {4, 1, 2, 1, 1, 2};
    
    // initializing second array
    vector<int> b = {3, 6, 3, 3};
    
    // calling function and printing result
    if(findSwapValues(a, b))
        cout << "True";  
    else
        cout << "False"; 
    
    return 0;
}
Java
// Java code naive solution to find a pair swapping which makes sum of arrays sum.
import java.util.*;

public class GFG {
    // Function to calculate sum of elements of array
    public static boolean findSwapValues(int[] a, int[] b) {
        // getting sizes of both arrays
        int n = a.length;
        int m = b.length;

        // calculating sum of elements of both arrays
        int sum1 = 0, sum2 = 0;
        for (int i = 0; i < n; i++)
            sum1 += a[i];

        for (int j = 0; j < m; j++)
            sum2 += b[j];

        // variables to store new sums after swapping
        int newsum1, newsum2;

        // traversing each element of first array
        for (int i = 0; i < n; i++) {
            // traversing each element of second array
            for (int j = 0; j < m; j++) {
                // calculating new sum if a[i] and b[j] are swapped
                newsum1 = sum1 - a[i] + b[j];
                newsum2 = sum2 - b[j] + a[i];

                // checking if both sums become equal
                if (newsum1 == newsum2) {
                    return true; // valid pair found
                }
            }
        }

        // if no such pair exists
        return false;
    }

    public static void main(String[] args) {
        // initializing first array
        int[] a = {4, 1, 2, 1, 1, 2};

        // initializing second array
        int[] b = {3, 6, 3, 3};

        // calling function and printing result
        if (findSwapValues(a, b))
            System.out.println("True");
        else
            System.out.println("False");
    }
}
Python
# Python code naive solution to find a pair swapping which makes sum of arrays sum.

# Function to calculate sum of elements of array
def findSwapValues(a, b):
    # getting sizes of both arrays
    n = len(a)
    m = len(b)

    # calculating sum of elements of both arrays
    sum1 = sum(a)
    sum2 = sum(b)

    # variables to store new sums after swapping
    newsum1, newsum2 = 0, 0

    # traversing each element of first array
    for i in range(n):
        # traversing each element of second array
        for j in range(m):
            # calculating new sum if a[i] and b[j] are swapped
            newsum1 = sum1 - a[i] + b[j]
            newsum2 = sum2 - b[j] + a[i]

            # checking if both sums become equal
            if newsum1 == newsum2:
                return True  # valid pair found

    # if no such pair exists
    return False

# Driver code
if __name__ == '__main__':
    # initializing first array
    a = [4, 1, 2, 1, 1, 2]

    # initializing second array
    b = [3, 6, 3, 3]

    # calling function and printing result
    if findSwapValues(a, b):
        print("True")
    else:
        print("False")
C#
// C# code naive solution to find a pair swapping which makes sum of arrays sum.
using System;
using System.Collections.Generic;

public class GFG {
    // Function to calculate sum of elements of array
    public static bool FindSwapValues(int[] a, int[] b) {
        // getting sizes of both arrays
        int n = a.Length;
        int m = b.Length;

        // calculating sum of elements of both arrays
        int sum1 = 0, sum2 = 0;
        for (int i = 0; i < n; i++)
            sum1 += a[i];

        for (int j = 0; j < m; j++)
            sum2 += b[j];

        // variables to store new sums after swapping
        int newsum1, newsum2;

        // traversing each element of first array
        for (int i = 0; i < n; i++) {
            // traversing each element of second array
            for (int j = 0; j < m; j++) {
                // calculating new sum if a[i] and b[j] are swapped
                newsum1 = sum1 - a[i] + b[j];
                newsum2 = sum2 - b[j] + a[i];

                // checking if both sums become equal
                if (newsum1 == newsum2) {
                    return true; // valid pair found
                }
            }
        }

        // if no such pair exists
        return false;
    }

    public static void Main() {
        // initializing first array
        int[] a = {4, 1, 2, 1, 1, 2};

        // initializing second array
        int[] b = {3, 6, 3, 3};

        // calling function and printing result
        if (FindSwapValues(a, b))
            Console.WriteLine("True");
        else
            Console.WriteLine("False");
    }
}
JavaScript
// JavaScript code naive solution to find a pair swapping which makes sum of arrays sum.

// Function to calculate sum of elements of array
function findSwapValues(a, b) {
    // getting sizes of both arrays
    let n = a.length;
    let m = b.length;

    // calculating sum of elements of both arrays
    let sum1 = a.reduce((acc, val) => acc + val, 0);
    let sum2 = b.reduce((acc, val) => acc + val, 0);

    // variables to store new sums after swapping
    let newsum1, newsum2;

    // traversing each element of first array
    for (let i = 0; i < n; i++) {
        // traversing each element of second array
        for (let j = 0; j < m; j++) {
            // calculating new sum if a[i] and b[j] are swapped
            newsum1 = sum1 - a[i] + b[j];
            newsum2 = sum2 - b[j] + a[i];

            // checking if both sums become equal
            if (newsum1 === newsum2) {
                return true; // valid pair found
            }
        }
    }

    // if no such pair exists
    return false;
}

// Driver code
let a = [4, 1, 2, 1, 1, 2];
let b = [3, 6, 3, 3];

if (findSwapValues(a, b)) {
    console.log("True");
} else {
    console.log("False");
}

Output
True

[Better Approach] Using Sorting + Two Pointer Technique - O(n log n) Time and O(1) Space

Let the sum of array a[] be sumA and sum of array b[] be sumB, then we need to find a value x in a[] and a y in b[] 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 sort the arrays and traverse 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.

Working of Approach:

  • Calculate the sum of both arrays sum1 and sum2, and check if their difference is even.
  • Compute target = (sum1 - sum2) / 2.
  • Sort both arrays to apply the two-pointer technique.
  • Initialize two pointers i and j at the start of both arrays.
  • Traverse and compare a[i] - b[j] with target to find a valid pair.
  • If a match is found return true, otherwise move pointers accordingly; if none found, return false.
C++
#include <bits/stdc++.h>
using namespace std;

// function to calculate sum of elements of array
int getSum(vector<int> &arr)
{
    int sum = 0;
    for (int i = 0; i < arr.size(); i++)
        sum += arr[i];
    return sum;
}

// function to get target value
// a - b = (sum1 - sum2) / 2
int getTarget(vector<int> &a, vector<int> &b)
{
    int sum1 = getSum(a);
    int sum2 = getSum(b);

    // if difference is odd, equal sum not possible
    if ((sum1 - sum2) % 2 != 0)
        return INT_MIN;

    return (sum1 - sum2) / 2;
}

bool findSwapValues(vector<int> &a, vector<int> &b)
{
    int n = a.size();
    int m = b.size();

    // sorting both arrays
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());

    // getting target difference
    int target = getTarget(a, b);

    // check only invalid case
    if (target == INT_MIN)
        return false;

    int i = 0, j = 0;

    // using two pointer approach
    while (i < n && j < m)
    {
        int diff = a[i] - b[j];

        if (diff == target)
            return true;
        else if (diff < target)
            i++;
        else
            j++;
    }

    return false;
}

// Driver code
int main() {

    vector<int> a = {4, 1, 2, 1, 1, 2};
    vector<int> b = {3, 6, 3, 3};

    bool ans = findSwapValues(a, b);

    if(ans)
        cout << "True";
    else
        cout << "False";
    
    return 0;
}
Java
import java.util.Arrays;

public class GFG {
    // function to calculate sum of elements of array
    public static int getSum(int[] arr) {
        int sum = 0;
        for (int i = 0; i < arr.length; i++)
            sum += arr[i];
        return sum;
    }

    // function to get target value
    // a - b = (sum1 - sum2) / 2
    public static int getTarget(int[] a, int[] b) {
        int sum1 = getSum(a);
        int sum2 = getSum(b);

        // if difference is odd, equal sum not possible
        if ((sum1 - sum2) % 2!= 0)
            return Integer.MIN_VALUE;

        return (sum1 - sum2) / 2;
    }

    public static boolean findSwapValues(int[] a, int[] b) {
        int n = a.length;
        int m = b.length;

        // sorting both arrays
        Arrays.sort(a);
        Arrays.sort(b);

        // getting target difference
        int target = getTarget(a, b);

        // check only invalid case
        if (target == Integer.MIN_VALUE)
            return false;

        int i = 0, j = 0;

        // using two pointer approach
        while (i < n && j < m) {
            int diff = a[i] - b[j];

            if (diff == target)
                return true;
            else if (diff < target)
                i++;
            else
                j++;
        }

        return false;
    }

    public static void main(String[] args) {
        int[] a = {4, 1, 2, 1, 1, 2};
        int[] b = {3, 6, 3, 3};

        boolean ans = findSwapValues(a, b);

        if(ans)
            System.out.println("True");
        else
            System.out.println("False");
    }
}
Python
def getSum(arr):
    # function to calculate sum of elements of array
    sum = 0
    for i in range(len(arr)):
        sum += arr[i]
    return sum

def getTarget(a, b):
    # function to get target value
    # a - b = (sum1 - sum2) / 2
    sum1 = getSum(a)
    sum2 = getSum(b)

    # if difference is odd, equal sum not possible
    if (sum1 - sum2) % 2!= 0:
        return float('-inf')

    return (sum1 - sum2) // 2

def findSwapValues(a, b):
    n = len(a)
    m = len(b)

    # sorting both arrays
    a.sort()
    b.sort()

    # getting target difference
    target = getTarget(a, b)

    # check only invalid case
    if target == float('-inf'):
        return False

    i = 0
    j = 0

    # using two pointer approach
    while i < n and j < m:
        diff = a[i] - b[j]

        if diff == target:
            return True
        elif diff < target:
            i += 1
        else:
            j += 1

    return False

# Driver code
a = [4, 1, 2, 1, 1, 2]
b = [3, 6, 3, 3]
ans = findSwapValues(a, b)
if ans:
    print('True')
else:
    print('False')
C#
using System;
using System.Linq;

public class GFG
{
    // function to calculate sum of elements of array
    public static int GetSum(int[] arr)
    {
        int sum = 0;
        for (int i = 0; i < arr.Length; i++)
            sum += arr[i];
        return sum;
    }

    // function to get target value
    // a - b = (sum1 - sum2) / 2
    public static int GetTarget(int[] a, int[] b)
    {
        int sum1 = GetSum(a);
        int sum2 = GetSum(b);

        // if difference is odd, equal sum not possible
        if ((sum1 - sum2) % 2!= 0)
            return int.MinValue;

        return (sum1 - sum2) / 2;
    }

    public static bool FindSwapValues(int[] a, int[] b)
    {
        int n = a.Length;
        int m = b.Length;

        // sorting both arrays
        Array.Sort(a);
        Array.Sort(b);

        // getting target difference
        int target = GetTarget(a, b);

        // check only invalid case
        if (target == int.MinValue)
            return false;

        int i = 0, j = 0;

        // using two pointer approach
        while (i < n && j < m)
        {
            int diff = a[i] - b[j];

            if (diff == target)
                return true;
            else if (diff < target)
                i++;
            else
                j++;
        }

        return false;
    }

    public static void Main(string[] args)
    {
        int[] a = { 4, 1, 2, 1, 1, 2 };
        int[] b = { 3, 6, 3, 3 };

        bool ans = FindSwapValues(a, b);

        if (ans)
            Console.WriteLine("True");
        else
            Console.WriteLine("False");
    }
}
JavaScript
function getSum(arr) {
    // function to calculate sum of elements of array
    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    return sum;
}

function getTarget(a, b) {
    // function to get target value
    // a - b = (sum1 - sum2) / 2
    let sum1 = getSum(a);
    let sum2 = getSum(b);

    // if difference is odd, equal sum not possible
    if ((sum1 - sum2) % 2!= 0) {
        return Number.NEGATIVE_INFINITY;
    }

    return Math.floor((sum1 - sum2) / 2);
}

function findSwapValues(a, b) {
    let n = a.length;
    let m = b.length;

    // sorting both arrays
    a.sort((x, y) => x - y);
    b.sort((x, y) => x - y);

    // getting target difference
    let target = getTarget(a, b);

    // check only invalid case
    if (target === Number.NEGATIVE_INFINITY) {
        return false;
    }

    let i = 0, j = 0;

    // using two pointer approach
    while (i < n && j < m) {
        let diff = a[i] - b[j];

        if (diff === target) {
            return true;
        } else if (diff < target) {
            i++;
        } else {
            j++;
        }
    }

    return false;
}

// Driver code
let a = [4, 1, 2, 1, 1, 2];
let b = [3, 6, 3, 3];

let ans = findSwapValues(a, b);
if (ans) {
    console.log('True');
} else {
    console.log('False');
}

Output
True

[Expected Approach] Using Hashing (Unordered Set) - O(n + m) Time and O(n) Space

Let sumA and sumB be the sums of arrays a[] and b[]. To make both sums equal after swapping elements x and y, the condition becomes sumA - x + y = sumB - y + x. Simplifying this, we get x - y = (sumA - sumB) / 2. Let this value be the target. Now, the problem reduces to finding a pair (x, y) such that x = target + y. We store all elements of a[] in a hash set and check for each element of b[] whether the required value exists in the set.

Working of Approach:

  • Calculate sums of both arrays sumA and sumB.
  • If their difference is odd, return false.
  • Compute target = (sumA - sumB) / 2.
  • Store elements of a[] in a hash set.
  • For each element in b[], check if target + b[j] exists in the set.
  • If found, return true, otherwise return false.
C++
#include <bits/stdc++.h>
using namespace std;

bool findSwapValues(vector<int> &a, vector<int> &b)
{

    // getting sizes of both arrays
    int n = a.size();
    int m = b.size();

    // calculating sum of elements of both arrays
    int sumA = 0, sumB = 0;
    for (int i = 0; i < n; i++)
        sumA += a[i];

    for (int j = 0; j < m; j++)
        sumB += b[j];

    // if difference of sums is odd, equal sum is not possible
    if ((sumA - sumB) % 2 != 0)
        return false;

    // creating a hash set to store elements of array a[]
    unordered_set<int> possibleX;

    // inserting all elements of a[] into hash set
    for (int i = 0; i < n; i++)
    {
        possibleX.insert(a[i]);
    }

    // traversing array b[] to find required pair
    for (int j = 0; j < m; j++)
    {

        // calculating value of x using formula
        int X = (sumA - sumB) / 2 + b[j];

        // checking if this value exists in array a[]
        if (possibleX.find(X) != possibleX.end())
        {
            return true; // valid pair found
        }
    }

    // if no such pair exists
    return false;
}
// Driver Code
int main() {
    
    vector<int> a = {4, 1, 2, 1, 1, 2};
    vector<int> b = {3, 6, 3, 3};
    
    bool ans = findSwapValues(a, b);
    
    if(ans)
        cout << "True";
    else
        cout << "False";
    
    return 0;
}
Java
import java.util.HashSet;

public class GFG {
    public static boolean findSwapValues(int[] a, int[] b) {
        // getting sizes of both arrays
        int n = a.length;
        int m = b.length;

        // calculating sum of elements of both arrays
        int sumA = 0, sumB = 0;
        for (int i = 0; i < n; i++)
            sumA += a[i];

        for (int j = 0; j < m; j++)
            sumB += b[j];

        // if difference of sums is odd, equal sum is not possible
        if ((sumA - sumB) % 2!= 0)
            return false;

        // creating a hash set to store elements of array a[]
        HashSet<Integer> possibleX = new HashSet<>();

        // inserting all elements of a[] into hash set
        for (int i = 0; i < n; i++) {
            possibleX.add(a[i]);
        }

        // traversing array b[] to find required pair
        for (int j = 0; j < m; j++) {
            // calculating value of x using formula
            int X = (sumA - sumB) / 2 + b[j];

            // checking if this value exists in array a[]
            if (possibleX.contains(X)) {
                return true; // valid pair found
            }
        }

        // if no such pair exists
        return false;
    }

    public static void main(String[] args) {
        int[] a = {4, 1, 2, 1, 1, 2};
        int[] b = {3, 6, 3, 3};

        boolean ans = findSwapValues(a, b);

        if (ans)
            System.out.println("True");
        else
            System.out.println("False");
    }
}
Python
def findSwapValues(a, b):
    # getting sizes of both arrays
    n = len(a)
    m = len(b)

    # calculating sum of elements of both arrays
    sumA = sum(a)
    sumB = sum(b)

    # if difference of sums is odd, equal sum is not possible
    if (sumA - sumB) % 2!= 0:
        return False

    # creating a set to store elements of array a[]
    possibleX = set(a)

    # traversing array b[] to find required pair
    for j in range(m):
        # calculating value of x using formula
        X = (sumA - sumB) // 2 + b[j]

        # checking if this value exists in array a[]
        if X in possibleX:
            return True  # valid pair found

    # if no such pair exists
    return False

# Driver Code
a = [4, 1, 2, 1, 1, 2]
b = [3, 6, 3, 3]

ans = findSwapValues(a, b)

if ans:
    print('True')
else:
    print('False')
C#
using System;
using System.Collections.Generic;

class GFG
{
    static bool findSwapValues(List<int> a, List<int> b)
    {
        // getting sizes of both arrays
        int n = a.Count;
        int m = b.Count;

        // calculating sum of elements of both arrays
        int sumA = 0, sumB = 0;
        for (int i = 0; i < n; i++)
            sumA += a[i];

        for (int j = 0; j < m; j++)
            sumB += b[j];

        // if difference of sums is odd, equal sum is not possible
        if ((sumA - sumB) % 2!= 0)
            return false;

        // creating a hash set to store elements of array a[]
        HashSet<int> possibleX = new HashSet<int>();

        // inserting all elements of a[] into hash set
        for (int i = 0; i < n; i++)
        {
            possibleX.Add(a[i]);
        }

        // traversing array b[] to find required pair
        for (int j = 0; j < m; j++)
        {
            // calculating value of x using formula
            int X = (sumA - sumB) / 2 + b[j];

            // checking if this value exists in array a[]
            if (possibleX.Contains(X))
            {
                return true; // valid pair found
            }
        }

        // if no such pair exists
        return false;
    }

    // Driver Code
    static void Main(string[] args)
    {
        List<int> a = new List<int> { 4, 1, 2, 1, 1, 2 };
        List<int> b = new List<int> { 3, 6, 3, 3 };

        bool ans = findSwapValues(a, b);

        Console.WriteLine(ans ? "True" : "False");
    }
}
JavaScript
function findSwapValues(a, b) {

    // getting sizes of both arrays
    const n = a.length;
    const m = b.length;

    // calculating sum of elements of both arrays
    let sumA = 0, sumB = 0;
    for (let i = 0; i < n; i++)
        sumA += a[i];

    for (let j = 0; j < m; j++)
        sumB += b[j];

    // if difference of sums is odd, equal sum is not possible
    if ((sumA - sumB) % 2!== 0)
        return false;

    // creating a set to store elements of array a[]
    const possibleX = new Set();

    // inserting all elements of a[] into set
    for (let i = 0; i < n; i++)
        possibleX.add(a[i]);

    // traversing array b[] to find required pair
    for (let j = 0; j < m; j++)
    {
        // calculating value of x using formula
        const X = (sumA - sumB) / 2 + b[j];

        // checking if this value exists in array a[]
        if (possibleX.has(X))
        {
            return true; // valid pair found
        }
    }

    // if no such pair exists
    return false;
}
// Driver Code
const a = [4, 1, 2, 1, 1, 2];
const b = [3, 6, 3, 3];

const ans = findSwapValues(a, b);

console.log(ans ? 'True' : 'False');

Output
True
Comment