Check if two arrays can be made equal by reversing any subarray once | C ++ implementation to check whether two arrays can be made equal by reversing a sub - array only once ; Function to check whether two arrays can be made equal by reversing a sub - array only once ; Integer variable for storing the required starting and ending indices in the array ; Finding the smallest index for which A [ i ] != B [ i ] i . e the starting index of the unequal sub - array ; Finding the largest index for which A [ i ] != B [ i ] i . e the ending index of the unequal sub - array ; Reversing the sub - array A [ start ] , A [ start + 1 ] . . A [ end ] ; Checking whether on reversing the sub - array A [ start ] ... A [ end ] makes the arrays equal ; If any element of the two arrays is unequal print No and return ; Print Yes if arrays are equal after reversing the sub - array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkArray ( int A [ ] , int B [ ] , int N ) { int start = 0 ; int end = N - 1 ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != B [ i ] ) { start = i ; break ; } } for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( A [ i ] != B [ i ] ) { end = i ; break ; } } reverse ( A + start , A + end + 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] != B [ i ] ) { cout << " No " << endl ; return ; } } cout << " Yes " << endl ; } int main ( ) { int A [ ] = { 1 , 3 , 2 , 4 } ; int B [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; checkArray ( A , B , N ) ; return 0 ; }