Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if Arrays can be made equal by Replacing elements with their number of Digits
Next article icon

Check if two arrays can be made equal by reversing any subarray once

Last Updated : 17 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays A[] and B[] of equal size N, the task is to check whether A[] can be made equal to B[] by reversing any sub-array of A only once. 
 

Examples: 

Input: A[] = {1, 3, 2, 4} 
B[] = {1, 2, 3, 4} 
Output: Yes 
Explanation: 
The sub-array {3, 2} can be reversed to {2, 3}, which makes A equal to B.
 

Input: A[] = {1, 4, 2, 3} 
B[] = {1, 2, 3, 4} 
Output: No 
Explanation: 
There is no sub-array of A which, when reversed, makes A equal to B.

Naive Approach: Check for all sub-arrays of A[] and compare the two arrays after reversing the sub-array. 
Time complexity: O(N2).
 

Efficient Approach: 

  • First, find the starting and the ending index of the sub-array not equal in A and B.
  • Then, by reversing the required sub-array, we can check whether A can be made equal to B or not.
  • The starting index is the first index in the arrays for which A[i] != B[i] and the ending index is the last index in arrays for which A[i] != B[i]. 
     

Below is the implementation of the above approach.

C++




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

Java




// Java implementation to
// check whether two arrays
// can be made equal by
// reversing a sub-array
// only once
import java.util.*;
class GFG{
  
// Function to check whether two arrays
// can be made equal by reversing
// a sub-array only once
static void checkArray(int A[], int B[], int N)
{
    // Integer variable for
    // storing the required
    // starting and ending
    // indices in the array
    int start = 0;
    int end = N - 1;
  
    // Finding the smallest index
    // for which A[i] != B[i]
    // i.e the starting index
    // of the unequal sub-array
    for (int i = 0; i < N; i++)
    {
        if (A[i] != B[i])
        {
            start = i;
            break;
        }
    }
    // Finding the largest index
    // for which A[i] != B[i]
    // i.e the ending index
    // of the unequal sub-array
    for (int i = N - 1; i >= 0; i--)
    {
        if (A[i] != B[i])
        {
            end = i;
            break;
        }
    }
  
    // Reversing the sub-array
    // A[start], A[start+1] .. A[end]
    Collections.reverse(Arrays.asList(A));
  
    // Checking whether on reversing
    // the sub-array A[start]...A[end]
    // makes the arrays equal
    for (int i = 0; i < N; i++)
    {
        if (A[i] != B[i])
        {
            // If any element of the
            // two arrays is unequal
            // print No and return
            System.out.println("No");
            return;
        }
    }
    // Print Yes if arrays are
    // equal after reversing
    // the sub-array
   System.out.println("Yes");
}
// Driver code
public static void main(String[] args)
{
    int A[] = { 1, 3, 2, 4 };
    int B[] = { 1, 2, 3, 4 };
    int N = A.length;
    checkArray(A, B, N);
}
}
 
// This Code is contributed by rock_cool
 
 

Python3




# Python3 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
def checkArray(A, B, N):
     
    # Integer variable for
    # storing the required
    # starting and ending
    # indices in the array
    start = 0
    end = N - 1
 
    # Finding the smallest index
    # for which A[i] != B[i]
    # i.e the starting index
    # of the unequal sub-array
    for i in range(N):
        if (A[i] != B[i]):
            start = i
            break
             
    # Finding the largest index
    # for which A[i] != B[i]
    # i.e the ending index
    # of the unequal sub-array
    for i in range(N - 1, -1, -1):
        if (A[i] != B[i]):
            end = i
            break
 
    # Reversing the sub-array
    # A[start], A[start+1] .. A[end]
    A[start:end + 1] = reversed(A[start:end + 1])
     
    # Checking whether on reversing
    # the sub-array A[start]...A[end]
    # makes the arrays equal
    for i in range(N):
        if (A[i] != B[i]):
             
            # If any element of the
            # two arrays is unequal
            # print No and return
            print("No")
            return
             
    # Print Yes if arrays are
    # equal after reversing
    # the sub-array
    print("Yes")
     
# Driver code
if __name__ == '__main__':
     
    A = [ 1, 3, 2, 4 ]
    B = [ 1, 2, 3, 4 ]
    N = len(A)
     
    checkArray(A, B, N)
     
# This code is contributed by mohit kumar 29
 
 

C#




// C# implementation to
// check whether two arrays
// can be made equal by
// reversing a sub-array
// only once
using System;
 
class GFG{
 
// Function to check whether two arrays
// can be made equal by reversing
// a sub-array only once
static void checkArray(int []A, int []B, int N)
{
     
    // Integer variable for
    // storing the required
    // starting and ending
    // indices in the array
    int start = 0;
    int end = N - 1;
 
    // Finding the smallest index
    // for which A[i] != B[i]
    // i.e the starting index
    // of the unequal sub-array
    for(int i = 0; i < N; i++)
    {
        if (A[i] != B[i])
        {
            start = i;
            break;
        }
    }
     
    // Finding the largest index
    // for which A[i] != B[i]
    // i.e the ending index
    // of the unequal sub-array
    for(int i = N - 1; i >= 0; i--)
    {
        if (A[i] != B[i])
        {
            end = i;
            break;
        }
    }
 
    // Reversing the sub-array
    // A[start], A[start+1] .. A[end]
    Array.Reverse(A, start, end);
 
 
    // Checking whether on reversing
    // the sub-array A[start]...A[end]
    // makes the arrays equal
    for(int i = 0; i < N; i++)
    {
        if (A[i] != B[i])
        {
             
            // If any element of the
            // two arrays is unequal
            // print No and return
            Console.Write("No");
            return;
        }
    }
     
    // Print Yes if arrays are
    // equal after reversing
    // the sub-array
    Console.Write("Yes");
}
 
// Driver code
public static void Main(string[] args)
{
    int []A = { 1, 3, 2, 4 };
    int []B = { 1, 2, 3, 4 };
    int N = A.Length;
    checkArray(A, B, N);
}
}
 
// This code is contributed by rutvik_56
 
 

Javascript




<script>
 
 
// Javascript 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
function checkArray(A, B, N)
{
    // Integer variable for
    // storing the required
    // starting and ending
    // indices in the array
    var start = 0;
    var end = N - 1;
 
    // Finding the smallest index
    // for which A[i] != B[i]
    // i.e the starting index
    // of the unequal sub-array
    for (var i = 0; i < N; i++) {
        if (A[i] != B[i]) {
            start = i;
            break;
        }
    }
    // Finding the largest index
    // for which A[i] != B[i]
    // i.e the ending index
    // of the unequal sub-array
    for (var i = N - 1; i >= 0; i--) {
        if (A[i] != B[i]) {
            end = i;
            break;
        }
    }
 
    // Reversing the sub-array
    // A[start], A[start+1] .. A[end]
    var l = start;
    var r = end;
    var d = parseInt((r-l+2)/2);
      for(var i=0;i<d;i++)
      {
         var t = A[l+i];
         A[l+i] = A[r-i];
         A[r-i] = t;
      }
 
    // Checking whether on reversing
    // the sub-array A[start]...A[end]
    // makes the arrays equal
 
    for (var i = 0; i < N; i++) {
        if (A[i] != B[i]) {
            // If any element of the
            // two arrays is unequal
            // print No and return
            document.write( "No" );
            return;
        }
    }
    // Print Yes if arrays are
    // equal after reversing
    // the sub-array
    document.write( "Yes" );
}
// Driver code
var A = [1, 3, 2, 4];
var B = [1, 2, 3, 4];
var N = A.length;
checkArray(A, B, N);
 
 
</script>
 
 
Output: 
Yes

 

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



Next Article
Check if Arrays can be made equal by Replacing elements with their number of Digits

C

codeku
Improve
Article Tags :
  • Arrays
  • Data Structures
  • DSA
  • Searching
  • Reverse
  • subarray
Practice Tags :
  • Arrays
  • Data Structures
  • Reverse
  • Searching

Similar Reads

  • Check if two arrays can be made equal by reversing subarrays multiple times
    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: YesExplanation: Reverse subarrays in array B as shown below:Reverse subarray [3, 1], B becomes [1, 3, 2]Re
    10 min read
  • Check if two strings can be made equal by reversing a substring of one of the strings
    Given two strings X and Y of length N, the task is to check if both the strings can be made equal by reversing any substring of X exactly once. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: X = "adcbef", Y = "abcdef"Output: YesExplanation: Strings can be made equal by
    12 min read
  • Check if MEX of an Array can be changed with atmost one Subarray replacement
    Given an array arr[] of size N, the task is to check if can you change the MEX of the array to MEX + 1 by replacing at most one subarray with any positive integer. Follow 0-based indexing. Note: The MEX of the array is the smallest non-negative number that is not present in the array. Examples: Inpu
    11 min read
  • Check if any subarray can be made palindromic by replacing less than half of its elements
    Given an array arr[] of size N, the task is to check if any subarray from the given array can be made a palindrome by replacing less than half of its elements (i.e. floor[length/2]) by any other element of the subarray. Examples: Input: arr[] = {2, 7, 4, 6, 7, 8}Output: YesExplanation: Among all sub
    7 min read
  • Check if Arrays can be made equal by Replacing elements with their number of Digits
    Given two arrays A[] and B[] of length N, the task is to check if both arrays can be made equal by performing the following operation at most K times: Choose any index i and either change Ai to the number of digits Ai have or change Bi to the number of digits Bi have. Examples: Input: N = 4, K = 1,
    10 min read
  • Check if two strings can be made equal by swapping pairs of adjacent characters
    Given two strings A and B of length N and M respectively and an array arr[] consisting of K integers, the task is to check if the string B can be obtained from the string A by swapping any pair of adjacent characters of the string A any number of times such that the swapped indices are not present i
    15+ min read
  • Check if reversing a sub array make the array sorted
    Given an array of n distinct integers. The task is to check whether reversing any one sub-array can make the array sorted or not. If the array is already sorted or can be made sorted by reversing any one subarray, print "Yes", else print "No". Examples: Input : arr [] = {1, 2, 5, 4, 3}Output : YesBy
    15+ min read
  • Check if Array Elemnts can be Made Equal with Given Operations
    Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X. Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.Note : Only one operation can be performed on a numbe
    6 min read
  • Check if a string can be made equal to another string by swapping or replacement of characters
    Given two strings S1 and S2, the task is to check if string S1 can be made equal to string S2 by swapping any pair of characters replacing any character in the string S1. If it is possible to make the string S1 equal to S2, then print "Yes". Otherwise, print "No". Examples: Input: S1 = “abc”, S2 = “
    8 min read
  • Find if array can be divided into two subarrays of equal sum
    Given an array of integers, find if it's possible to remove exactly one integer from the array that divides the array into two subarrays with the same sum. Examples: Input: arr = [6, 2, 3, 2, 1] Output: true Explanation: On removing element 2 at index 1, the array gets divided into two subarrays [6]
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences