Sort an array by swapping elements of different type specified by another array

Given two arrays a[] and b[] which contain the integer elements and their respective types (either type 0 or type 1) respectively, the task is to check if it is possible to sort the array in non-decreasing order by swapping elements of different types only.Â
Examples:Â
Â
Input: a[] = {30, 20, 20, 10}, b[] = {1, 1, 1, 1}Â
Output: NoÂ
Explanation:Â
Since all elements are of same type, no swaps are allowed and the given array is not sorted in non-decreasing order.
Input: a[] = {6, 5, 4}, b[] = {1, 1, 0}Â
Output: YesÂ
Explanation:Â
Swap 4 and 6 to convert the array into non-decreasing order.Â
Â
Â
Approach:
To solve the problem mentioned above, the following observations need to be made:Â
Â
- If the array a[] is already sorted in non-decreasing order, then the answer is Yes.
- If the array a[] is not sorted and all the elements are of the same type, then the answer is No as no swaps are possible.
- In any other case, the answer is Yes as we can always sort the array. This is because we will have at least one element whose type is different from the other elements, so we can swap it with all the other elements any number of times till all the elements are in their sorted position.
Below is the implementation of the above approach:Â
Â
C++
// C++ program to check if it// is possible to sort the// array in non-decreasing// order by swapping// elements of different typesÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to check if it is// possible to sort the array// in non-decreasing order by// swapping elements of// different typesbool sorting_possible(int a[],                      int b[], int n){    // Consider the array    // to be already sorted    bool sorted = true;Â
    int type1 = 0, type0 = 0, i;Â
    // checking if array is    // already sorted    for (i = 1; i < n; i++) {        // Check for a pair which        // is in decreasing order        if (a[i] < a[i - 1]) {Â
            sorted = false;            break;        }    }Â
    // Count the frequency of    // each type of element    for (i = 0; i < n; i++) {        // type0 stores count        // of elements of type 0        if (b[i] == 0)            type0++;Â
        // type1 stores count        // of elements of type 1        else            type1++;    }Â
    // Return true if array    // is already sorted    if (sorted)        return true;Â
    // Return false if all    // elements are of same    // type and array    // is unsorted    else if (type1 == n             || type0 == n)        return false;Â
    // Possible for all    // other cases    else        return true;}Â
// Driver Programint main(){Â Â Â Â int a[] = { 15, 1, 2, 17, 6 };Â Â Â Â int b[] = { 1, 1, 0, 1, 1 };Â Â Â Â int n = sizeof(a) / sizeof(a[0]);Â
    bool res = sorting_possible(a, b, n);Â
    if (res)        cout << "Yes";    else        cout << "No";} |
Java
// Java program to check if it is // possible to sort the array in // non-decreasing order by swapping// elements of different typesimport java.util.*;Â
class GFG{Â
// Function to check if it is// possible to sort the array// in non-decreasing order by// swapping elements of// different typesstatic boolean sorting_possible(int a[],                                int b[],                                 int n){         // Consider the array    // to be already sorted    boolean sorted = true;Â
    int type1 = 0, type0 = 0, i;Â
    // Checking if array is    // already sorted    for(i = 1; i < n; i++)    {                // Check for a pair which       // is in decreasing order       if (a[i] < a[i - 1])        {           sorted = false;           break;       }    }Â
    // Count the frequency of    // each type of element    for(i = 0; i < n; i++)    {                // type0 stores count       // of elements of type 0       if (b[i] == 0)           type0++;             // type1 stores count       // of elements of type 1       else           type1++;    }Â
    // Return true if array    // is already sorted    if (sorted)        return true;Â
    // Return false if all elements    // are of same type and array    // is unsorted    else if (type1 == n || type0 == n)        return false;Â
    // Possible for all    // other cases    else        return true;}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int a[] = { 15, 1, 2, 17, 6 };Â Â Â Â int b[] = { 1, 1, 0, 1, 1 };Â Â Â Â int n = a.length;Â Â Â Â Â Â Â Â Â boolean res = sorting_possible(a, b, n);Â
    if (res)        System.out.print("Yes");    else        System.out.print("No");}}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 program to check if it# is possible to sort the# array in non-decreasing# order by swapping# elements of different typesÂ
# Function to check if it is# possible to sort the array# in non-decreasing order by# swapping elements of different typesdef sorting_possible(a, b, n):         # Consider the array    # to be already sorted    sorted = True         type1 = 0    type0 = 0         # Checking if array is    # already sorted    for i in range(1, n):                 # Check for a pair which        # is in decreasing order        if (a[i] < a[i - 1]):            sorted = False            break         # Count the frequency of    # each type of element    for i in range(n):                 # type0 stores count        # of elements of type 0        if (b[i] == 0):            type0 += 1                 # type1 stores count        # of elements of type 1        else:            type1 += 1         # Return true if array    # is already sorted    if (sorted != False):        return True         # Return false if all elements    # are of same type and array    # is unsorted    elif (type1 == n or type0 == n):        return False             # Possible for all    # other cases    else:        return True     # Driver codea = [ 15, 1, 2, 17, 6 ]b = [ 1, 1, 0, 1, 1 ]Â
n = len(a)res = sorting_possible(a, b, n)Â
if (res != False):Â Â Â Â print("Yes")else:Â Â Â Â print("No") Â Â Â Â Â # This code is contributed by sanjoy_62 |
C#
// C# program to check if it is // possible to sort the array in // non-decreasing order by swapping// elements of different typesusing System;Â
class GFG{Â
// Function to check if it is// possible to sort the array// in non-decreasing order by// swapping elements of// different typesstatic bool sorting_possible(int []a,                             int []b,                              int n){         // Consider the array    // to be already sorted    bool sorted = true;Â
    int type1 = 0, type0 = 0, i;Â
    // Checking if array is    // already sorted    for(i = 1; i < n; i++)    {               // Check for a pair which       // is in decreasing order       if (a[i] < a[i - 1])        {           sorted = false;           break;       }    }Â
    // Count the frequency of    // each type of element    for(i = 0; i < n; i++)    {               // type0 stores count       // of elements of type 0       if (b[i] == 0)           type0++;                   // type1 stores count       // of elements of type 1       else           type1++;    }Â
    // Return true if array    // is already sorted    if (sorted)        return true;Â
    // Return false if all elements    // are of same type and array    // is unsorted    else if (type1 == n || type0 == n)        return false;Â
    // Possible for all    // other cases    else        return true;}Â
// Driver codepublic static void Main(String[] args){Â Â Â Â int []a = { 15, 1, 2, 17, 6 };Â Â Â Â int []b = { 1, 1, 0, 1, 1 };Â Â Â Â int n = a.Length;Â Â Â Â Â Â Â Â Â bool res = sorting_possible(a, b, n);Â
    if (res)        Console.Write("Yes");    else        Console.Write("No");}}Â
// This code is contributed by Rajput-Ji |
Javascript
<script>Â Â Â Â Â // Javascript program to check if it is // possible to sort the array in // non-decreasing order by swapping// elements of different typesÂ
// Function to check if it is// possible to sort the array// in non-decreasing order by// swapping elements of// different typesfunction sorting_possible(a,b, n){           // Consider the array    // to be already sorted    let sorted = true;       let type1 = 0, type0 = 0, i;       // Checking if array is    // already sorted    for(i = 1; i < n; i++)    {                 // Check for a pair which       // is in decreasing order       if (a[i] < a[i - 1])        {           sorted = false;           break;       }    }       // Count the frequency of    // each type of element    for(i = 0; i < n; i++)    {                 // type0 stores count       // of elements of type 0       if (b[i] == 0)           type0++;                     // type1 stores count       // of elements of type 1       else           type1++;    }       // Return true if array    // is already sorted    if (sorted)        return true;       // Return false if all elements    // are of same type and array    // is unsorted    else if (type1 == n || type0 == n)        return false;       // Possible for all    // other cases    else        return true;}  // Driver code    let a = [ 15, 1, 2, 17, 6 ];    let b = [ 1, 1, 0, 1, 1 ];    let n = a.length;           let res = sorting_possible(a, b, n);       if (res)        document.write("Yes");    else        document.write("No");Â
// This code is contributed by souravghosh0416.</script> |
Yes
Â
Illustration:Â
Â
a[] = {15, 1, 2, 17, 6}Â
Only 2 is of type 0 and rest are of type 1.Â
Hence the following steps leads to a sorted array:Â
15, 1, 2, 17, 6 – > 15, 1, 6, 17, 2Â
15, 1, 6, 17, 2 -> 15, 1, 6, 2, 17Â
15, 1, 6, 2, 17 -> 2, 1, 6, 15, 17Â
2, 1, 6, 15, 17 -> 1, 2, 6, 15, 17Â
Â
Time Complexity: O(n)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



