The Wayback Machine - https://web.archive.org/web/20240913193243/https://www.geeksforgeeks.org/find-a-pair-swapping-which-makes-sum-of-two-arrays-same/
Open In App

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

Last Updated : 05 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
23.94%
1.3L

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)



Similar Reads

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[] = {1, 2, 3, 4}, arr2[] = {2, 1, 4, 3}, N = 4Outpu
12 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 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 &lt;= i &lt;= 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 sum of arrA[] and arrB[] after swapping, then find t
7 min read
Find side of Square which makes minimal area to fit two identical rectangles inside it
Given height H, and width W, of a rectangle, the task is to find the side of a square of the minimum area in which two rectangles fit completely. Note: Two rectangles can touch each other by side or corner.Rectangles cannot intersect each other.Rectangles can also touch the sides of the square but must be completely inside it.The Rectangles can be
12 min read
Maximize M such that swapping arr[i] with arr[i+M] makes Array sorted
Given a permutation arr[] of size N which is unsorted and contains all integers from 1 to N exactly once, the task is to find the maximum value of M such that performing a swap of arr[i] with arr[i+M] for any i in the range [1, N-M] makes the array sorted. Examples: Input: arr[] = {4, 2, 3, 1}Output: 3Explanation: Permutation can be sorted by swapp
5 min read
Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Check if given strings can be made same by swapping two characters of same or different strings
Given an array of equal-length strings, arr[] of size N, the task is to check if all the strings can be made equal by repeatedly swapping any pair of characters of same or different strings from the given array. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { "acbdd", "abcee" } Output: YES Explanation: Swapp
11 min read
Given two strings check which string makes a palindrome first
Given two strings 'A' and 'B' of equal length. Two players play a game where they both pick a character from their respective strings (First picks from A and second from B) and put into a third string (which is initially empty). The player that can make the third string palindrome, is winner. If first player makes palindrome first then print 'A', e
6 min read
Print indices of array elements whose removal makes the sum of odd and even-indexed elements equal
Given an array arr[] of size N, the task is to find indices of array elements whose removal makes the sum of odd and even indexed elements equal. If no such element exists, then print -1. Examples: Input: arr[] = {4, 1, 6, 2} Output: 1 Explanation: Removing arr[1] modifies arr[] to {4, 6, 2} Sum of even-indexed array elements = arr[0] + arr[2] = 4
13 min read
Find Bit whose minimum sequence flips makes all bits same
Given a binary string consisting only of 1's and 0's. Find the bit (output is either 1 or 0)whose minimum number of contiguous sequence flips can make all bits of the string same.Here, contiguous sequence flip means flipping a substring or 0s or 1s. For Example, in the string "00011110001110", in one flip we can change the string to "11111110001110
6 min read
Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted
Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted. Examples: If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between indexes 3 and 8.If the input array is [0, 1, 15, 25,
15+ min read
Count elements of same value placed at same indices of two given arrays
Given two arrays A[] and B[] of N unique elements, the task is to find the maximum number of matched elements from the two given arrays. Elements of the two arrays are matched if they are of the same value and can be placed at the same index (0-based indexing).(By right shift or left shift of the two arrays). Examples: Input: A[] = { 5, 3, 7, 9, 8
8 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 : a[] = {5, 4, 13, 1} b[] = {3, 2, 6, 1}Output : 3
15+ min read
Divide array into two arrays which does not contain any pair with sum K
Given an array arr[] consisting of N non-negative distinct integers and an integer K, the task is to distribute the array in two arrays such that both the arrays does not contain a pair with sum K. Examples: Input: arr[] = {1, 0, 2, 3, 4, 7, 8, 9}, K = 4Output: 3, 2, 4, 7, 8, 9 0, 1 Explanation: Pairs (1, 3) and (0, 4) from the given array cannot b
6 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 : arr1[] = {10, 2, 3}, arr2[] = {3, 4, 7} Output : M
6 min read
Count characters of a string which when removed individually makes the string equal to another string
Given two strings A and B of size N and M respectively, the task is to count characters of the string A, which when removed individually makes both the strings equal. If there exists several such characters, then print their respective positions. Otherwise, print "-1". Examples: Input: A = "abaac", B = "abac"Output: 2 3 4Explanation: Following remo
8 min read
Which sorting algorithm makes minimum number of memory writes?
Minimizing the number of writes is useful when making writes to some huge data set is very expensive, such as with EEPROMs or Flash memory, where each write reduces the lifespan of the memory. Among the sorting algorithms that we generally study in our data structure and algorithm courses,  Selection Sort makes least number of writes (it makes O(n)
1 min read
Derive a MultiSet from given Array such that sum is &gt; P and removing any element makes sum &lt; P
Given an array arr[] of N elements, the task is to derive a MultiSet having the numbers from the given array in possible repetitions, such that the sum of the MultiSet is strictly greater than given number P and if any of the element is removed, then the sum becomes strictly less than P. Print the number of times the corresponding element of given
10 min read
Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array
Given two sorted arrays A[] and B[] of size N, the task is to check if it is possible to merge two given sorted arrays into a new sorted array such that no two consecutive elements are from the same array. Examples: Input: A[] = {3, 5, 8}, B[] = {2, 4, 6}Output: Yes Explanation: Merged array = {B[0], A[0], B[1], A[1], B[2], A[2]} Since the resultan
15+ min read
Find the element whose multiplication with -1 makes array sum 0
Given an array of N integers. The task is to find the smallest index of an element such that when multiplied by -1 the sum of whole array becomes 0. If there is no such index return -1. Examples: Input : arr[] = {1, 3, -5, 3, 4}Output : 2Input : arr[] = {5, 3, 6, -7, -4}Output : -1Recommended: Please try your approach on {IDE} first, before moving
10 min read
Javascript Program For Swapping Nodes In A Linked List Without Swapping Data
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields. It may be assumed that all keys in the linked list are distinct. Examples: Input : 10-&gt;15-&gt;12-&gt;13-&gt;20-&gt;14, x = 12, y = 20Output: 1
6 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 possible rearrangements of B[] is {1, 2, 3, 4, 4}. Th
5 min read
Rearrange two given arrays such that sum of same indexed elements lies within given range
Given two arrays arr1[] and arr2[] consisting of N positive integers and an even integer K, the task is to check if the sum of the same indexed elements in the two arrays lie in the range [K/2, K] after rearranging the given arrays or not. If it is possible to obtain such an arrangement, then print "Yes". Otherwise, print "No". Examples: Input: arr
6 min read
Construct two N-length arrays with same-indexed elements as co-prime and a difference of N in their sum
Given a positive integer N, the task is to generate two arrays of length N such that the same-indexed elements of both the arrays are co-prime and absolute difference between the sum of elements of the arrays is N. Examples: Input: N = 5Output: {1, 3, 5, 7, 9} {2, 4, 6, 8, 10}Explanation: Pairs of same-indexed elements are (1, 2), (3, 4), (5, 6), (
6 min read
Maximize sum of product of same-indexed elements of equal length subarrays obtained from two given arrays
Given two arrays arr[] and brr[] of size N and M integers respectively, the task is to maximize the sum of the product of the same-indexed elements of two subarrays of an equal length with the selected subarray from the array brr[] being reversed. Examples: Input: arr[] = {-1, 3, -2, 4, 5}, brr[] = {4, -5}Output: 26Explanation:Subarrays selected fr
13 min read
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, 3}, arr2[] = {2, 3, 4, 1}Output: 0Explanation: Su
9 min read
Reduce sum of same-indexed elements of two arrays to less than K by rearranging the second array
Given two arrays arr1[] and arr2[], both of size N and an integer X, the task is to check if the sum of same-indexed elements of both the arrays at corresponding indices can be made at most K after rearranging the second array. If it is possible then print "Yes" else print "No". Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 1, 2}, X = 4Output:
6 min read
Minimize sum of absolute differences of same-indexed elements of two given arrays by at most one replacement
Given two arrays A[] and B[] of size N each, the task is to find the minimum possible sum of absolute difference of same indexed elements of the two arrays, i.e. sum of |A[i] - B[i]| for all i such that 0 ? i &lt; N by replacing at most one element in A[] with another element of A[]. Examples: Input: A[] = {6, 4, 1, 9, 7, 5}, B[] = {3, 9, 7, 4, 2,
10 min read
Python List Comprehension to find pair with given sum from two arrays
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to x. Examples: Input : arr1 = [-1, -2, 4, -6, 5, 7] arr2 = [6, 3, 4, 0] x = 8 Output : [(5, 3), (4, 4)] Input : arr1 = [1, 2, 4, 5, 7] arr2 = [5, 6, 3, 4, 8] x = 9 Output : [(1, 8), (4, 5), (5, 4)] We have existing solution for this pr
2 min read
Find maximum sum pair with same digit sum
Given an array arr having N integers, the task is to find a pair with maximum sum and having the same sum of digits. Print the sum of that pair, if it exists. Otherwise, print -1. Examples: Input: arr[]={55, 23, 32, 46, 88}Output: 46 55 101Explanation: Pair {55, 46} will give the sum of 55 + 46 = 101 Input: arr[]={18, 19, 23, 15}Output: -1 Approach
7 min read
Article Tags :
Practice Tags :