Skip to content
Related Articles

Related Articles

Check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array
  • Difficulty Level : Expert
  • Last Updated : 18 Feb, 2021

Given an array A[] of size N and a binary array B[] of size N, the task is to check if the array A[] can be converted into a sorted array by swapping pairs (A[i], A[j]) if B[i] is not equal to B[j]. If the array A[] can be sorted, then print “Yes“. Otherwise, print “No“.

Examples:

Input: A[] = {3, 1, 2}, B[] = {0, 1, 1}
Output: Yes
Explanation:
Swap element at position 1 and position 2 of A[] since B[1]!=B[2]. So, A[] = {1, 3, 2}, B[] = {1, 0, 1}
Now, swap element at position 2 and position 3 of A[] since B[2]!=B[3]. So, A[] = {1, 2, 3}. Hence, it is sorted.

Input: A[] = {5, 15, 4}, B[] = {0, 0, 0}
Output: No

Approach: The problem can be solved based on the following observations:



If at least two elements of the array, B[] are different, then it is possible to swap any two elements of the array A[].

Follow the steps below to solve the problem:

  • Check if the given array A[] is already sorted in ascending order or not. If found to be true, then print “Yes”.
  • Otherwise, count the number of 1s and 0s present in the array B[].
    • If the array B[] contains at least one 0 and one 1, then print “Yes”.
    • Otherwise, print “No”.

Below is the implementation of the above approach:

C++




// C++ Program for above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if array, A[] can be converted
// into sorted array by swapping (A[i], A[j]) if B[i]
// not equal to B[j]
bool checkifSorted(int A[], int B[], int N)
{
 
  // Stores if array A[] is sorted
  // in descending order or not
  bool flag = false;
 
  // Traverse the array A[]
  for (int i = 0; i < N - 1; i++) {
 
    // If A[i] is greater than A[i + 1]
    if (A[i] > A[i + 1]) {
 
      // Update flag
      flag = true;
      break;
    }
  }
 
  // If array is sorted
  // in ascending order
  if (!flag) {
    return true;
  }
 
  // count = 2: Check if 0s and 1s
  // both present in the B[]
  int count = 0;
 
  // Traverse the array
  for (int i = 0; i < N; i++) {
 
    // If current element is 0
    if (B[i] == 0) {
 
      // Update count
      count++;
      break;
    }
  }
 
 
  // Traverse the array B[]
  for (int i = 0; i < N; i++) {
 
    // If current element is 1
    if (B[i] == 1) {
      count++;
      break;
    }
  }
 
  // If both 0s and 1s are present
  // in the array
  if (count == 2) {
    return true;
  }
  return false;
}
 
// Driver Code
int main()
{
  // Input array A[]
  int A[] = { 3, 1, 2 };
 
  // Input array B[]
  int B[] = { 0, 1, 1 };
 
  int N = sizeof(A) / sizeof(A[0]);
  // Function call
  bool check = checkifSorted(A, B, N);
 
  // If true,print YES
  if (check) {
    cout << "YES" <<endl;
  }
  // Else print NO
  else {
    cout << "NO" <<endl;
  }
 
  return 0;
}

Java




// Java program of the above approach
import java.io.*;
 
class GFG {
 
     
    // Function to check if array, A[] can be converted
    // into sorted array by swapping (A[i], A[j]) if B[i]
    // not equal to B[j]
    static boolean checkifSorted(int A[], int B[], int N)
    {
         
        // Stores if array A[] is sorted
        // in descending order or not
        boolean flag = false;
 
        // Traverse the array A[]
        for (int i = 0; i < N - 1; i++) {
 
            // If A[i] is greater than A[i + 1]
            if (A[i] > A[i + 1]) {
 
                // Update flag
                flag = true;
                break;
            }
        }
 
        // If array is sorted
        // in ascending order
        if (!flag) {
            return true;
        }
 
        // count = 2: Check if 0s and 1s
        // both present in the B[]
        int count = 0;
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
             
            // If current element is 0
            if (B[i] == 0) {
                 
                // Update count
                count++;
                break;
            }
        }
         
         
        // Traverse the array B[]
        for (int i = 0; i < N; i++) {
             
            // If current element is 1
            if (B[i] == 1) {
                count++;
                break;
            }
        }
 
        // If both 0s and 1s are present
        // in the array
        if (count == 2) {
            return true;
        }
        return false;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Input array A[]
        int A[] = { 3, 1, 2 };
 
        // Input array B[]
        int B[] = { 0, 1, 1 };
 
        int N = A.length;
        // Function call
        boolean check = checkifSorted(A, B, N);
 
        // If true,print YES
        if (check) {
            System.out.println("YES");
        }
        // Else print NO
        else {
            System.out.println("NO");
        }
    }
}

Python3




# Python program of the above approach
     
# Function to check if array, A[] can be converted
# into sorted array by swapping (A[i], A[j]) if B[i]
# not equal to B[j]
def checkifSorted(A, B, N):
   
  # Stores if array A[] is sorted
  # in descending order or not
  flag = False
 
  # Traverse the array A[]
  for i in range( N - 1):
     
    # If A[i] is greater than A[i + 1]
    if (A[i] > A[i + 1]):
       
      # Update flag
      flag = True
      break
 
  # If array is sorted
  # in ascending order
  if (not flag):
    return True
 
  # count = 2: Check if 0s and 1s
  # both present in the B[]
  count = 0
 
  # Traverse the array
  for i in range(N):
     
    # If current element is 0
    if (B[i] == 0):
       
      # Update count
      count += 1
      break
         
  # Traverse the array B[]
  for i in range(N):
     
    # If current element is 1
    if B[i]:
      count += 1
      break
       
  # If both 0s and 1s are present
  # in the array
  if (count == 2):
    return True
       
  return False
 
# Driver Code
# Input array A[]
A = [ 3, 1, 2 ]
 
# Input array B[]
B = [ 0, 1, 1 ]
N = len(A)
 
# Function call
check = checkifSorted(A, B, N)
 
# If true,print YES
if (check):
  print("YES")
         
# Else print NO
else:
  print("NO")
  
# This code is contributed by rohitsingh07052

C#




// C# program of the above approach
using System;
public class GFG
{
     
    // Function to check if array, A[] can be converted
    // into sorted array by swapping (A[i], A[j]) if B[i]
    // not equal to B[j]
    static bool checkifSorted(int []A, int []B, int N)
    {
         
        // Stores if array A[] is sorted
        // in descending order or not
        bool flag = false;
 
        // Traverse the array A[]
        for (int i = 0; i < N - 1; i++) {
 
            // If A[i] is greater than A[i + 1]
            if (A[i] > A[i + 1]) {
 
                // Update flag
                flag = true;
                break;
            }
        }
 
        // If array is sorted
        // in ascending order
        if (!flag) {
            return true;
        }
 
        // count = 2: Check if 0s and 1s
        // both present in the B[]
        int count = 0;
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
             
            // If current element is 0
            if (B[i] == 0) {
                 
                // Update count
                count++;
                break;
            }
        }
         
         
        // Traverse the array B[]
        for (int i = 0; i < N; i++)
        {
             
            // If current element is 1
            if (B[i] == 1)
            {
                count++;
                break;
            }
        }
 
        // If both 0s and 1s are present
        // in the array
        if (count == 2)
        {
            return true;
        }
        return false;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        // Input array A[]
        int []A = { 3, 1, 2 };
 
        // Input array B[]
        int []B = { 0, 1, 1 };
        int N = A.Length;
         
        // Function call
        bool check = checkifSorted(A, B, N);
 
        // If true,print YES
        if (check) {
            Console.WriteLine("YES");
        }
        // Else print NO
        else {
            Console.WriteLine("NO");
        }
    }
}
 
// This code is contributed by AnkThon
Output: 
YES

 

Time Complexity: O(N)
Auxiliary Space: O(1)

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :