Skip to content
Related Articles

Related Articles

Convert one array to another using adjacent swaps of elements
  • Last Updated : 10 Aug, 2020

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:

  1. Create two arrays(say even[] and odd[]) insert all the even and odd numbers from arr1[] in even[] and odd[] respectively.
  2. Now check whether the even and odd numbers in arr2[] are in the same order as in even[] and odd[].
  3. 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++




// 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 operations
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<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
    // avaialble 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 Code
int 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




// Java program for the above approach
import java.util.*;
  
class GFG{
  
// Function which checks if it is
// possible to convert arr1[] to
// arr2[] by given operations
static 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
    // avaialble 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 Code
public 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




# Python3 program for the above approach
  
# Function which checks if it is
# possible to convert arr1[] to
# arr2[] by given operations
def 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
    # avaialble 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 Code
if __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#




// C# program for the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function which checks if it is
// possible to convert arr1[] to
// arr2[] by given operations
static 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
    // avaialble 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 Code
public 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
Output: 
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.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live and Geeks Classes Live USA

My Personal Notes arrow_drop_up
Recommended Articles
Page :