Check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array
Last Updated :
06 Nov, 2023
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++
#include <bits/stdc++.h>
using namespace std;
bool checkifSorted( int A[], int B[], int N)
{
bool flag = false ;
for ( int i = 0; i < N - 1; i++) {
if (A[i] > A[i + 1]) {
flag = true ;
break ;
}
}
if (!flag) {
return true ;
}
int count = 0;
for ( int i = 0; i < N; i++) {
if (B[i] == 0) {
count++;
break ;
}
}
for ( int i = 0; i < N; i++) {
if (B[i] == 1) {
count++;
break ;
}
}
if (count == 2) {
return true ;
}
return false ;
}
int main()
{
int A[] = { 3, 1, 2 };
int B[] = { 0, 1, 1 };
int N = sizeof (A) / sizeof (A[0]);
bool check = checkifSorted(A, B, N);
if (check) {
cout << "YES" <<endl;
}
else {
cout << "NO" <<endl;
}
return 0;
}
|
Java
import java.io.*;
class GFG {
static boolean checkifSorted( int A[], int B[], int N)
{
boolean flag = false ;
for ( int i = 0 ; i < N - 1 ; i++) {
if (A[i] > A[i + 1 ]) {
flag = true ;
break ;
}
}
if (!flag) {
return true ;
}
int count = 0 ;
for ( int i = 0 ; i < N; i++) {
if (B[i] == 0 ) {
count++;
break ;
}
}
for ( int i = 0 ; i < N; i++) {
if (B[i] == 1 ) {
count++;
break ;
}
}
if (count == 2 ) {
return true ;
}
return false ;
}
public static void main(String[] args)
{
int A[] = { 3 , 1 , 2 };
int B[] = { 0 , 1 , 1 };
int N = A.length;
boolean check = checkifSorted(A, B, N);
if (check) {
System.out.println( "YES" );
}
else {
System.out.println( "NO" );
}
}
}
|
Python3
def checkifSorted(A, B, N):
flag = False
for i in range ( N - 1 ):
if (A[i] > A[i + 1 ]):
flag = True
break
if ( not flag):
return True
count = 0
for i in range (N):
if (B[i] = = 0 ):
count + = 1
break
for i in range (N):
if B[i]:
count + = 1
break
if (count = = 2 ):
return True
return False
A = [ 3 , 1 , 2 ]
B = [ 0 , 1 , 1 ]
N = len (A)
check = checkifSorted(A, B, N)
if (check):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
public class GFG
{
static bool checkifSorted( int []A, int []B, int N)
{
bool flag = false ;
for ( int i = 0; i < N - 1; i++) {
if (A[i] > A[i + 1]) {
flag = true ;
break ;
}
}
if (!flag) {
return true ;
}
int count = 0;
for ( int i = 0; i < N; i++) {
if (B[i] == 0) {
count++;
break ;
}
}
for ( int i = 0; i < N; i++)
{
if (B[i] == 1)
{
count++;
break ;
}
}
if (count == 2)
{
return true ;
}
return false ;
}
public static void Main( string [] args)
{
int []A = { 3, 1, 2 };
int []B = { 0, 1, 1 };
int N = A.Length;
bool check = checkifSorted(A, B, N);
if (check) {
Console.WriteLine( "YES" );
}
else {
Console.WriteLine( "NO" );
}
}
}
|
Javascript
<script>
function checkifSorted(A , B , N) {
var flag = false ;
for (i = 0; i < N - 1; i++) {
if (A[i] > A[i + 1]) {
flag = true ;
break ;
}
}
if (!flag) {
return true ;
}
var count = 0;
for (i = 0; i < N; i++) {
if (B[i] == 0) {
count++;
break ;
}
}
for (i = 0; i < N; i++) {
if (B[i] == 1) {
count++;
break ;
}
}
if (count == 2) {
return true ;
}
return false ;
}
var A = [ 3, 1, 2 ];
var B = [ 0, 1, 1 ];
var N = A.length;
var check = checkifSorted(A, B, N);
if (check) {
document.write( "YES" );
}
else {
document.write( "NO" );
}
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach 2:
Here’s another approach to solve the problem:
- Create a vector of pairs to store both the elements and their respective types (0 or 1) from arrays A and B.
- Sort the vector in descending order based on the elements of A.
- Traverse the sorted vector and check if the type of the current element is 0. If it is, then we have found the first unsorted element that needs to be swapped.
- Traverse the rest of the vector and check if any other element with type 1 is present. If it is, then swap the elements and return “YES”. If not, return “NO”.
Here’s the code for the same approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkIfSorted( int A[], int B[], int N) {
vector<pair< int , int >> vec;
for ( int i = 0; i < N; i++) {
vec.push_back({A[i], B[i]});
}
sort(vec.rbegin(), vec.rend());
int unsortedIndex = -1;
for ( int i = 0; i < N - 1; i++) {
if (vec[i].second > vec[i + 1].second) {
unsortedIndex = i;
break ;
}
}
if (unsortedIndex == -1) {
return true ;
}
for ( int i = unsortedIndex + 1; i < N; i++) {
if (vec[i].second == 1) {
swap(vec[unsortedIndex].first, vec[i].first);
break ;
}
}
for ( int i = 0; i < N - 1; i++) {
if (vec[i].first > vec[i + 1].first) {
return false ;
}
}
return true ;
}
int main() {
int A[] = {3, 1, 2};
int B[] = {0, 1, 1};
int N = sizeof (A) / sizeof (A[0]);
bool check = checkIfSorted(A, B, N);
if (check) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
return 0;
}
|
Java
import java.util.*;
class Main {
static boolean checkIfSorted( int [] A, int [] B, int N) {
List<Pair<Integer, Integer>> vec = new ArrayList<>();
for ( int i = 0 ; i < N; i++) {
vec.add( new Pair<>(A[i], B[i]));
}
vec.sort((a, b) -> Integer.compare(b.getKey(), a.getKey()));
int unsortedIndex = - 1 ;
for ( int i = 0 ; i < N - 1 ; i++) {
if (vec.get(i).getValue() > vec.get(i + 1 ).getValue()) {
unsortedIndex = i;
break ;
}
}
if (unsortedIndex == - 1 ) {
return true ;
}
for ( int i = unsortedIndex + 1 ; i < N; i++) {
if (vec.get(i).getValue() == 1 ) {
Collections.swap(vec, unsortedIndex, i);
break ;
}
}
for ( int i = 0 ; i < N - 1 ; i++) {
if (vec.get(i).getKey() > vec.get(i + 1 ).getKey()) {
return false ;
}
}
return true ;
}
public static void main(String[] args) {
int [] A = { 3 , 1 , 2 };
int [] B = { 0 , 1 , 1 };
int N = A.length;
boolean check = checkIfSorted(A, B, N);
if (check) {
System.out.println( "YES" );
} else {
System.out.println( "NO" );
}
}
static class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this .key = key;
this .value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
}
|
Python3
def checkIfSorted(A, B, N):
vec = []
for i in range (N):
vec.append([A[i], B[i]])
vec.sort(key = lambda x: x[ 0 ], reverse = True )
unsortedIndex = - 1
for i in range (N - 1 ):
if vec[i][ 1 ] > vec[i + 1 ][ 1 ]:
unsortedIndex = i
break
if unsortedIndex = = - 1 :
return True
for i in range (unsortedIndex + 1 , N):
if vec[i][ 1 ] = = 1 :
vec[unsortedIndex][ 0 ], vec[i][ 0 ] = vec[i][ 0 ], vec[unsortedIndex][ 0 ]
break
for i in range (N - 1 ):
if vec[i][ 0 ] > vec[i + 1 ][ 0 ]:
return False
return True
A = [ 3 , 1 , 2 ]
B = [ 0 , 1 , 1 ]
N = len (A)
check = checkIfSorted(A, B, N)
if check:
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static bool CheckIfSorted( int [] A, int [] B, int N)
{
List<Tuple< int , int >> vec = new List<Tuple< int , int >>();
for ( int i = 0; i < N; i++)
{
vec.Add( new Tuple< int , int >(A[i], B[i]));
}
vec = vec.OrderByDescending(x => x.Item1).ToList();
int unsortedIndex = -1;
for ( int i = 0; i < N - 1; i++)
{
if (vec[i].Item2 > vec[i + 1].Item2)
{
unsortedIndex = i;
break ;
}
}
if (unsortedIndex == -1)
{
return true ;
}
for ( int i = unsortedIndex + 1; i < N; i++)
{
if (vec[i].Item2 == 1)
{
Tuple< int , int > temp = vec[unsortedIndex];
vec[unsortedIndex] = Tuple.Create(vec[i].Item1, vec[unsortedIndex].Item2);
vec[i] = Tuple.Create(temp.Item1, vec[i].Item2);
break ;
}
}
for ( int i = 0; i < N - 1; i++)
{
if (vec[i].Item1 > vec[i + 1].Item1)
{
return false ;
}
}
return true ;
}
static void Main( string [] args)
{
int [] A = { 3, 1, 2 };
int [] B = { 0, 1, 1 };
int N = A.Length;
bool check = CheckIfSorted(A, B, N);
if (check)
{
Console.WriteLine( "YES" );
}
else
{
Console.WriteLine( "NO" );
}
}
}
|
Javascript
function checkIfSorted(A, B, N) {
let vec = [];
for (let i = 0; i < N; i++) {
vec.push([A[i], B[i]]);
}
vec.sort((a, b) => b[0] - a[0]);
let unsortedIndex = -1;
for (let i = 0; i < N - 1; i++) {
if (vec[i][1] > vec[i + 1][1]) {
unsortedIndex = i;
break ;
}
}
if (unsortedIndex === -1) {
return true ;
}
for (let i = unsortedIndex + 1; i < N; i++) {
if (vec[i][1] === 1) {
[vec[unsortedIndex][0], vec[i][0]] = [vec[i][0],
vec[unsortedIndex][0]];
break ;
}
}
for (let i = 0; i < N - 1; i++) {
if (vec[i][0] > vec[i + 1][0]) {
return false ;
}
}
return true ;
}
let A = [3, 1, 2];
let B = [0, 1, 1];
let N = A.length;
let check = checkIfSorted(A, B, N);
if (check) {
console.log( "YES" );
} else {
console.log( "NO" );
}
|
Output:
YES
Time Complexity: O(N log N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...