Given two integer arrays of equal length A and B. Find if the array A can be made equal to array B. If you can select any non-empty sub-array of A and reverse it. You are allowed to make any number of steps.
Examples :
Input : A = [11,9,3,4], B = [3,9,11,4] Output : YES Explanation : Reverse the subarray from index [1,3] Input : A = [11,9,4,3], B = [3,9,11,4] Output : YES Explanation : First Reverse the subarray from index [3,4], then reverse subarray [1,3]
Approach :
We can always achieve array B from A if the frequency of all the element of array B is same as array A, and there always exists a way to make them same cause we can perform the steps any number of time.
We use a count array to store the frequency of all the elements where the maximum value of the element is 10^4.
Implementation :
#include <bits/stdc++.h>
using namespace std;
vector<int> cnt(10001,0);
bool check(vector<int> A, vector<int> B){
for (int i = 0; i < A.size(); i++) {
cnt[B[i]] ++; cnt[A[i]] --;
}
for (int i = 1; i < 10001; i++) {
if (cnt[i] !=0)
return false ;
}
return true;
}
int main()
{
vector<int> A = {11,9,4,3};
vector<int> B = {3,9,11,4};
if( check(A, B) ){
cout<<"True"<<endl;
}
else{
cout<<"False"<<endl;
}
return 0;
}
Output :
True
Time Complexity : O(N)