Check if two arrays can be made equal by reversing subarrays multiple times
Last Updated :
06 Oct, 2023
Given two arrays A[] and B[], the task is to check if array B can be made equal to A by reversing the subarrays of B by any number of times.
Examples:
Input: A[] = {1 2 3}, B[] = {3 1 2}
Output: Yes
Explanation:
Reverse subarrays in array B as shown below:
Reverse subarray [3, 1], B becomes [1, 3, 2]
Reverse subarray [3, 2], B becomes [1, 2, 3] = A
There are multiple ways to convert B to A.
Input: A[] = {1 2 3}, B[] = {3 4 1 }
Output: No
Check if two arrays can be made equal by reversing subarrays multiple times using Sorting.
Since we have to make array B equal to array A only by reversing any sub array any number of times, Therefore it is possible only when both the arrays are anagrams. To check if both arrays are anagrams, we will sort both the arrays and check if at any index elements are not same then we will return false, otherwise we will return true at the end.
Below implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool canMadeEqual( int A[],
int B[], int n)
{
sort(A, A + n);
sort(B, B + n);
for ( int i = 0; i < n; i++)
if (A[i] != B[i])
return false ;
return true ;
}
int main()
{
int A[] = { 1, 2, 3 };
int B[] = { 1, 3, 2 };
int n = sizeof (A) / sizeof (A[0]);
if (canMadeEqual(A, B, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
C
#include<stdio.h>
#include<math.h>
int sort( int a[], int n)
{
int i, j, tmp;
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[j] <a[i])
{
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
return 0;
}
int canMadeEqual( int A[], int B[], int n)
{
int i;
sort(A, n);
sort(B, n);
for (i = 0; i < n; i++)
{
if (A[i] != B[i])
{
return (0);
}
}
return (1);
}
int main()
{
int A[] = { 1, 2, 3 };
int n;
int B[] = { 1, 3, 2 };
n = sizeof (A) / sizeof (A[0]);
if (canMadeEqual(A, B, n))
{
printf ( "Yes" );
}
else
{
printf ( "No" );
}
return 0;
}
|
Java
import java.util.*;
class GFG{
public static boolean canMadeEqual( int [] A,
int [] B,
int n)
{
Arrays.sort(A);
Arrays.sort(B);
for ( int i = 0 ; i < n; i++)
{
if (A[i] != B[i])
{
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
int A[] = { 1 , 2 , 3 };
int B[] = { 1 , 3 , 2 };
int n = A.length;
if (canMadeEqual(A, B, n))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
def canMadeEqual(A, B, n):
A.sort()
B.sort()
for i in range (n):
if (A[i] ! = B[i]):
return False
return True
if __name__ = = "__main__" :
A = [ 1 , 2 , 3 ]
B = [ 1 , 3 , 2 ]
n = len (A)
if (canMadeEqual(A, B, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool canMadeEqual( int [] A,
int [] B,
int n)
{
Array.Sort(A);
Array.Sort(B);
for ( int i = 0; i < n; i++)
{
if (A[i] != B[i])
{
return false ;
}
}
return true ;
}
public static void Main()
{
int [] A = { 1, 2, 3 };
int [] B = { 1, 3, 2 };
int n = A.Length;
if (canMadeEqual(A, B, n))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function canMadeEqual(A, B, n)
{
A.sort();
B.sort();
for ( var i = 0; i < n; i++)
if (A[i] != B[i])
return false ;
return true ;
}
var A = [ 1, 2, 3 ];
var B = [ 1, 3, 2 ];
var n = A.length;
if (canMadeEqual(A, B, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time complexity: O(N*Log N)
Auxiliary Space: O(1)
Check if two arrays can be made equal by reversing subarrays multiple times using Hashing.
- Create two hash tables, freqA and freqB, to store the frequency of elements in arrays A and B, respectively.
- Iterate over arrays A and B from index 0 to index n-1, and increment the frequency of the corresponding element in the respective hash table.
- Iterate over the elements in freqA.
- For each element in freqA, check if its frequency in freqB is the same as its frequency in freqA.
- If any frequency does not match, return false.
- If all frequencies match, return true.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <unordered_map>
using namespace std;
bool checkReverseSubarrays( int A[], int B[], int n) {
unordered_map< int , int > freqA, freqB;
for ( int i = 0; i < n; i++) {
freqA[A[i]]++;
freqB[B[i]]++;
}
for ( auto it = freqA.begin(); it != freqA.end(); it++) {
if (freqB[it->first] != it->second) {
return false ;
}
}
return true ;
}
int main() {
int A[] = {1, 2, 3};
int B[] = {1, 3, 2};
int n = sizeof (A) / sizeof (A[0]);
if (checkReverseSubarrays(A, B, n)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
|
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static boolean checkReverseSubarrays( int [] A, int [] B, int n) {
Map<Integer, Integer> freqA = new HashMap<>();
Map<Integer, Integer> freqB = new HashMap<>();
for ( int i = 0 ; i < n; i++) {
freqA.put(A[i], freqA.getOrDefault(A[i], 0 ) + 1 );
freqB.put(B[i], freqB.getOrDefault(B[i], 0 ) + 1 );
}
for (Map.Entry<Integer, Integer> entry : freqA.entrySet()) {
int element = entry.getKey();
int frequency = entry.getValue();
if (!freqB.containsKey(element) || freqB.get(element) != frequency) {
return false ;
}
}
return true ;
}
public static void main(String[] args) {
int [] A = { 1 , 2 , 3 };
int [] B = { 1 , 3 , 2 };
int n = A.length;
if (checkReverseSubarrays(A, B, n)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
}
}
|
Python3
def check_reverse_subarrays(A, B):
freqA = {}
freqB = {}
for num in A:
freqA[num] = freqA.get(num, 0 ) + 1
for num in B:
freqB[num] = freqB.get(num, 0 ) + 1
for num, freq in freqA.items():
if num not in freqB or freqB[num] ! = freq:
return False
return True
if __name__ = = "__main__" :
A = [ 1 , 2 , 3 ]
B = [ 1 , 3 , 2 ]
if check_reverse_subarrays(A, B):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
namespace ReverseSubarraysCheck
{
class Program
{
static bool CheckReverseSubarrays( int [] A, int [] B, int n)
{
Dictionary< int , int > freqA = new Dictionary< int , int >();
Dictionary< int , int > freqB = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
{
if (freqA.ContainsKey(A[i]))
{
freqA[A[i]]++;
}
else
{
freqA[A[i]] = 1;
}
if (freqB.ContainsKey(B[i]))
{
freqB[B[i]]++;
}
else
{
freqB[B[i]] = 1;
}
}
foreach ( var kvp in freqA)
{
if (!freqB.TryGetValue(kvp.Key, out int freqBValue) || freqBValue != kvp.Value)
{
return false ;
}
}
return true ;
}
static void Main( string [] args)
{
int [] A = { 1, 2, 3 };
int [] B = { 1, 3, 2 };
int n = A.Length;
if (CheckReverseSubarrays(A, B, n))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
}
|
Javascript
function checkReverseSubarrays(A, B) {
let freqA = {};
let freqB = {};
for (let num of A) {
freqA[num] = (freqA[num] || 0) + 1;
}
for (let num of B) {
freqB[num] = (freqB[num] || 0) + 1;
}
for (let num in freqA) {
if (!freqB.hasOwnProperty(num) || freqB[num] !== freqA[num]) {
return false ;
}
}
return true ;
}
const A = [1, 2, 3];
const B = [1, 3, 2];
if (checkReverseSubarrays(A, B)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
Output
Yes
Time Complexity: O(n), where n is the length of the arrays A and B,
Auxiliary Space: O(n) as we are using two hash tables to store the frequency of elements in A and B.
Share your thoughts in the comments
Please Login to comment...