Find a pair of elements swapping which makes sum of two arrays same
Last Updated :
05 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:
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
?>
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>
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)
Time Complexity: O(n + m)
Auxiliary Space: O(n)
Similar Reads
Minimum swaps of same-indexed elements required to make sum of two given arrays even
Given two arrays arr1[] and arr2[] of size N, the task is to count the minimum number of swaps of same-indexed elements from both the arrays arr1[] and arr2[] required to make the sum of all elements of both the arrays even. If it is not possible, then print "-1". Examples: Input: arr1[] = {1, 4, 2,
9 min read
Maximize sum of Averages of Pairs made using elements of X [] and Y []
Given two arrays X[] and Y[] of length N each. You can make a pair by selecting exactly one element from X[] and Y[]. The task is to find the maximum sum of averages by making N pairs. Examples: Input: N = 3, X[] = {6, 5, 4}, Y[] = {3, 1, 2}Output: 10Explanation: One of the possible way to arrange p
7 min read
Minimum sum of two elements from two arrays such that indexes are not same
Given two arrays a[] and b[] of same size. Task is to find minimum sum of two elements such that they belong to different arrays and are not at same index in their arrays. Examples: Input : a[] = {5, 4, 13, 2, 1} b[] = {2, 3, 4, 6, 5}Output : 3We take 1 from a[] and 2 from b[]Sum is 1 + 2 = 3.Input
15+ min read
Sum of middle elements of two sorted Arrays
Given two sorted arrays, arr1[] and arr2[], each of size N, the task is to merge the arrays and find the sum of the two middle elements of the merged array. Example: Input: N = 5, arr1[] = {1,2,4,6,10}, arr2[] = {4,5,6,9,12}Output: 11Explanation: The merged array is {1,2,4,4,5,6,6,9,10,12}. The sum
15 min read
Find pair i, j such that |A[i]âA[j]| is same as sum of difference of them with any Array element
Given an array A[] having N non-negative integers, find a pair of indices i and j such that the absolute difference between them is same as the sum of differences of those with any other array element i.e., | A[i] â A[k] | + | A[k]â A[j] | = | A[i] â A[j] |, where k can be any index. Examples: Input
7 min read
Rearrange two given arrays to maximize sum of same indexed elements
Given two arrays A[] and B[] of size N, the task is to find the maximum possible sum of abs(A[i] â B[i]) by rearranging the array elements. Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {1, 2, 3, 4, 5}Output: 12Explanation: One of the possible rearrangements of A[] is {5, 4, 3, 2, 1}. One of the pos
5 min read
Find Sum of pair from two arrays with maximum sum
Given two arrays of positive and distinct integers. The task is to find a pair from the two arrays with maximum sum. Note: The pair should contain one element from both the arrays. Examples: Input : arr1[] = {1, 2, 3}, arr2[] = {4, 5, 6} Output : Max Sum = 9 Pair (3, 6) has the maximum sum. Input :
6 min read
Minimize square sum of given Arrays by swapping elements at same indices
Given two arrays arrA[] and arrB[] containing N integers each. Perform the following operation any number of times (possibly zero): Select any index i (0 <= i <= N-1) andSwap arrA[i] and arrB[i]. The task is to find the minimum sum of the square of array sums i.e. if Sa and Sb are the array su
7 min read
Print the lexicographically smallest array by swapping elements whose sum is odd
Given an array of N integers. The task is to find the lexicographically smallest array possible by applying the given operation any number of times. The operation is to pick two elements ai and aj (1<=i, j<=N) such that ai + aj is odd, and then swap ai and aj. Examples: Input : a[] = {1, 5, 4,
6 min read
Count of possible unique arrays after swapping elements at same index of given Arrays
Given two arrays arr1[] and arr2[] with distinct elements of size N.The task is to count the total number of possible combinations after swapping elements at the same index of both the arrays such that there are no duplicates in both the arrays after performing the operation. Examples: Input: arr1[]
12 min read