Convert one array to another using adjacent swaps of elements - GeeksforGeeks

23 Aug, 2021
Given two arrays arr1[] and arr2[] of N integers. We can choose any two adjacent elements from array arr1[] and swap them if they are of opposite parity, the task is to check if it is possible to convert array arr1[] to array arr2[] by performing the given operation on arr1[]. Print “Yes” if it is possible to convert array arr1[] to arr2[] Else print “No”.Examples:  
Input: arr1[] = {5, 7, 8, 2, 10, 13}, arr2[] = {8, 5, 2, 7, 13, 10} Output: Yes Explanation: At first, swap 10 and 13 so arr1[] = [5, 7, 8, 2, 13, 10]. Now, swap 7 and 8 so arr1[] = [5, 8, 7, 2, 13, 10]. Now, swap 5 and 8 so arr1[] = [8, 5, 7, 2, 13, 10]. Now, swap 7 and 2 so arr1[] = [8, 5, 2, 7, 13, 10] = arr2[]. In each operation, we swap adjacent elements with different parity.Input: arr1[] = {0, 1, 13, 3, 4, 14, 6}, arr2[] = {0, 1, 14, 3, 4, 13, 6} Output: No Explanation: It is not possible to swap 13, 14 because they are not adjacent.  
Approach: The problem can be solved using Greedy Approach. Since we cannot swap any two even or odd numbers. So the relative position of both even and odd numbers in the arrays arr1[] and arr2[] must be exactly the same to make both the arrays equal with the given operation. Below are the steps: 
Create two arrays(say even[] and odd[]) insert all the even and odd numbers from arr1[] in even[] and odd[] respectively.Now check whether the even and odd numbers in arr2[] are in the same order as in even[] and odd[].If the above steps doesn’t gives any number from arr2[] which are not in the order of numbers in even[] and odd[] arrays respectively then, print “Yes” else print “No”.
Create two arrays(say even[] and odd[]) insert all the even and odd numbers from arr1[] in even[] and odd[] respectively.
Now check whether the even and odd numbers in arr2[] are in the same order as in even[] and odd[].
If the above steps doesn’t gives any number from arr2[] which are not in the order of numbers in even[] and odd[] arrays respectively then, print “Yes” else print “No”.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsvoid convert(int a[], int b[], int n){     // even[] will store the even    // elements of a[]     // odd[] will store the odd    // elements of a[]    vector<int> even, odd;     // Traverse a[] and insert the even    // and odd element respectively    for (int x = 0; x < n; x++) {         if (a[x] % 2 == 0)            even.push_back(a[x]);        else            odd.push_back(a[x]);    }     // ei points to the next    // available even element     // oi points to the next    // available odd element    int ei = 0, oi = 0;     // poss will store whether the    // given transformation    // of a[] to b[] is possible    bool poss = true;     // Traverse b[]    for (int x = 0; x < n; x++) {         if (b[x] % 2 == 0) {             // Check if both even            // elements are equal            if (ei < even.size()                && b[x] == even[ei]) {                ei++;            }            else {                poss = false;                break;            }        }        else {             // Check if both odd            // elements are equal            if (oi < odd.size()                && b[x] == odd[oi]) {                oi++;            }            else {                poss = false;                break;            }        }    }     // If poss is true, then we can    // transform a[] to b[]    if (poss)         cout << "Yes" << endl;     else         cout << "No" << endl;} // Driver Codeint main(){    // Given arrays    int arr1[] = { 0, 1, 13, 3, 4, 14, 6 };    int arr2[] = { 0, 1, 14, 3, 4, 13, 6 };     int N = sizeof(arr1) / sizeof(arr1[0]);     // Function Call    convert(arr1, arr2, N);     return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsstatic void convert(int a[], int b[], int n){         // even[] will store the even    // elements of a[]     // odd[] will store the odd    // elements of a[]    Vector<Integer> even = new Vector<Integer>(),                     odd = new Vector<Integer>();     // Traverse a[] and insert the even    // and odd element respectively    for(int x = 0; x < n; x++)    {       if (a[x] % 2 == 0)           even.add(a[x]);       else           odd.add(a[x]);    }     // ei points to the next    // available even element     // oi points to the next    // available odd element    int ei = 0, oi = 0;     // poss will store whether the    // given transformation    // of a[] to b[] is possible    boolean poss = true;     // Traverse b[]    for(int x = 0; x < n; x++)    {       if (b[x] % 2 == 0)       {                       // Check if both even           // elements are equal           if (ei < even.size() &&               b[x] == even.get(ei))           {               ei++;           }           else           {               poss = false;               break;           }       }       else       {                       // Check if both odd           // elements are equal           if (oi < odd.size() &&               b[x] == odd.get(oi))           {               oi++;           }           else           {               poss = false;               break;           }       }    }         // If poss is true, then we can    // transform a[] to b[]    if (poss)        System.out.print("Yes" + "\n");    else        System.out.print("No" + "\n");} // Driver Codepublic static void main(String[] args){         // Given arrays    int arr1[] = { 0, 1, 13, 3, 4, 14, 6 };    int arr2[] = { 0, 1, 14, 3, 4, 13, 6 };     int N = arr1.length;     // Function Call    convert(arr1, arr2, N);}} // This code is contributed by gauravrajput1
# Python3 program for the above approach # Function which checks if it is# possible to convert arr1[] to# arr2[] by given operationsdef convert(a, b, n):     # even[] will store the even    # elements of a[]     # odd[] will store the odd    # elements of a[]    even = []    odd = []     # Traverse a[] and insert the even    # and odd element respectively    for x in range(n):        if (a[x] % 2 == 0):            even.append(a[x])        else:            odd.append(a[x])     # ei points to the next    # available even element     # oi points to the next    # available odd element    ei, oi = 0, 0     # poss will store whether the    # given transformation    # of a[] to b[] is possible    poss = True     # Traverse b[]    for x in range(n):        if (b[x] % 2 == 0):             # Check if both even            # elements are equal            if (ei < len(even) and                 b[x] == even[ei]):                ei += 1                         else:                poss = False                break        else:             # Check if both odd            # elements are equal            if (oi < len(odd) and                 b[x] == odd[oi]):                oi += 1                         else:                poss = False                break     # If poss is true, then we can    # transform a[] to b[]    if (poss):        print("Yes")    else:        print("No") # Driver Codeif __name__ == "__main__":     # Given arrays    arr1 = [ 0, 1, 13, 3, 4, 14, 6 ]    arr2 = [ 0, 1, 14, 3, 4, 13, 6 ]     N = len(arr1)     # Function call    convert(arr1, arr2, N) # This code is contributed by chitranayal
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsstatic void convert(int []a, int []b, int n){         // even[] will store the even    // elements of []a     // odd[] will store the odd    // elements of []a    List<int> even = new List<int>(),               odd = new List<int>();     // Traverse []a and insert the even    // and odd element respectively    for(int x = 0; x < n; x++)    {        if (a[x] % 2 == 0)            even.Add(a[x]);        else            odd.Add(a[x]);    }     // ei points to the next    // available even element     // oi points to the next    // available odd element    int ei = 0, oi = 0;     // poss will store whether the    // given transformation    // of []a to []b is possible    bool poss = true;     // Traverse []b    for(int x = 0; x < n; x++)    {        if (b[x] % 2 == 0)        {                         // Check if both even            // elements are equal            if (ei < even.Count &&                b[x] == even[ei])            {                ei++;            }            else            {                poss = false;                break;            }        }        else        {                             // Check if both odd            // elements are equal            if (oi < odd.Count &&                b[x] == odd[oi])            {                oi++;            }            else            {                poss = false;                break;            }        }    }         // If poss is true, then we can    // transform []a to []b    if (poss)        Console.Write("Yes" + "\n");    else        Console.Write("No" + "\n");} // Driver Codepublic static void Main(String[] args){         // Given arrays    int []arr1 = { 0, 1, 13, 3, 4, 14, 6 };    int []arr2 = { 0, 1, 14, 3, 4, 13, 6 };     int N = arr1.Length;     // Function call    convert(arr1, arr2, N);}} // This code is contributed by gauravrajput1
<script> // JavaScript program for the above approach // Function which checks if it is// possible to convert arr1[] to// arr2[] by given operationsfunction convert(a, b, n){     // even[] will store the even    // elements of a[]     // odd[] will store the odd    // elements of a[]    var even = [], odd = [];     // Traverse a[] and insert the even    // and odd element respectively    for (var x = 0; x < n; x++) {         if (a[x] % 2 == 0)            even.push(a[x]);        else            odd.push(a[x]);    }     // ei points to the next    // available even element     // oi points to the next    // available odd element    var ei = 0, oi = 0;     // poss will store whether the    // given transformation    // of a[] to b[] is possible    var poss = true;     // Traverse b[]    for (var x = 0; x < n; x++) {         if (b[x] % 2 == 0) {             // Check if both even            // elements are equal            if (ei < even.length                && b[x] == even[ei]) {                ei++;            }            else {                poss = false;                break;            }        }        else {             // Check if both odd            // elements are equal            if (oi < odd.length                && b[x] == odd[oi]) {                oi++;            }            else {                poss = false;                break;            }        }    }     // If poss is true, then we can    // transform a[] to b[]    if (poss)         document.write( "Yes" );     else         document.write( "No" );} // Driver Code // Given arraysvar arr1 = [0, 1, 13, 3, 4, 14, 6 ];var arr2 = [0, 1, 14, 3, 4, 13, 6 ];var N = arr1.length; // Function Callconvert(arr1, arr2, N);  </script>
No
 
Time Complexity: O(N), where N is the number of elements in the array. Auxiliary Space: O(N), where N is the number of elements in the array. 
GauravRajput1
ukasp
rutvik_56
abhishek0719kadiyan
Arrays
Data Structures
Greedy Algorithms
Algorithms
Arrays
Data Structures
Data Structures
Arrays
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
K means Clustering - Introduction
Quadratic Probing in Hashing
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation