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 subarrays multiple times

Last Updated : 06 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
 

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++




// C++ implementation to check if
// two arrays can be made equal
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if array B
// can be made equal to array A
bool canMadeEqual(int A[],
                  int B[], int n)
{
    // sort both the arrays
    sort(A, A + n);
    sort(B, B + n);
 
    // Check if both the arrays
    // are equal or not
    for (int i = 0; i < n; i++)
        if (A[i] != B[i])
            return false;
    return true;
}
 
// Driver Code
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




// C implementation to check if 
// two arrays can be made equal
#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;
}
 
// Function to check if array B
// can be made equal to array A
int canMadeEqual(int A[], int B[], int n)
{
    int i;
     
    // Sort both arrays
    sort(A, n);
    sort(B, n);
     
    // Check both arrays equal or not
    for(i = 0; i < n; i++)
    {
        if (A[i] != B[i])
        {
            return(0);
        }
    }
    return (1);
}
 
// Driver Code
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;
}
 
// This code is contributed by adityakumar27200
 
 

Java




// Java implementation to check if
// two arrays can be made equal
import java.util.*;
 
class GFG{
     
// Function to check if array B
// can be made equal to array A
public static boolean canMadeEqual(int[] A,
                                   int[] B,
                                   int n)
{
     
    // Sort both the arrays
    Arrays.sort(A);
    Arrays.sort(B);
 
    // Check if both the arrays
    // are equal or not
    for(int i = 0; i < n; i++)
    {
        if (A[i] != B[i])
        {
            return false;
        }
    }
    return true;
}
 
// Driver code
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");
}
}
 
// This code is contributed by divyeshrabadiya07
 
 

Python3




# Python3 implementation to check if
# two arrays can be made equal
 
# Function to check if array B
# can be made equal to array A
def canMadeEqual(A, B, n):
   
  # Sort both the arrays
  A.sort()
  B.sort()
 
  # Check if both the arrays
  # are equal or not
  for i in range(n):
    if (A[i] != B[i]):
      return False
     
  return True
 
# Driver Code
if __name__ == "__main__":
   
  A = [ 1, 2, 3 ]
  B = [ 1, 3, 2 ]
  n = len(A)
 
  if (canMadeEqual(A, B, n)):
    print( "Yes")
  else:
    print("No")
 
# This code is contributed by chitranayal
 
 

C#




// C# implementation to check if
// two arrays can be made equal
using System;
 
class GFG{
 
// Function to check if array B
// can be made equal to array A
static bool canMadeEqual(int[] A,
                         int[] B,
                         int n)
{
     
    // Sort both the arrays
    Array.Sort(A);
    Array.Sort(B);
 
    // Check if both the arrays
    // are equal or not
    for(int i = 0; i < n; i++)
    {
        if (A[i] != B[i])
        {
            return false;
        }
    }
    return true;
}
 
// Driver code
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");
}
}
 
// This code is contributed by adityakumar27200
 
 

Javascript




<script>
 
 
// Javascript implementation to check if
// two arrays can be made equal
 
// Function to check if array B
// can be made equal to array A
function canMadeEqual(A, B, n)
{
    // sort both the arrays
    A.sort();
    B.sort();
 
    // Check if both the arrays
    // are equal or not
    for (var i = 0; i < n; i++)
        if (A[i] != B[i])
            return false;
    return true;
}
 
// Driver Code
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");
 
// This code is contributed by rutvik_56.
</script>
 
 
Output
Yes    

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) {
    // Create hash tables to store the frequency of elements in A and B
    unordered_map<int, int> freqA, freqB;
    for (int i = 0; i < n; i++) {
        freqA[A[i]]++;
        freqB[B[i]]++;
    }
 
    // Check if the frequencies of elements in A and B match
    for (auto it = freqA.begin(); it != freqA.end(); it++) {
        if (freqB[it->first] != it->second) {
            return false;
        }
    }
 
    // If frequencies match, return true
    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;
    }
 
    
}
// This code is contributed by rudra1807raj
 
 

Java




import java.util.HashMap;
import java.util.Map;
 
public class Main {
    // Function to check if two arrays are reversals of each other
    public static boolean checkReverseSubarrays(int[] A, int[] B, int n) {
        // Create hash maps to store the frequency of elements in A and B
        Map<Integer, Integer> freqA = new HashMap<>();
        Map<Integer, Integer> freqB = new HashMap<>();
 
        // Count the frequency of elements in arrays A and B
        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);
        }
 
        // Check if the frequencies of elements in A and B match
        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;
            }
        }
 
        // If frequencies match, return true
        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):
    # Create dictionaries to store the frequency of elements in A and B
    freqA = {}
    freqB = {}
 
    # Count the frequency of elements in arrays A and B
    for num in A:
        freqA[num] = freqA.get(num, 0) + 1
    for num in B:
        freqB[num] = freqB.get(num, 0) + 1
 
    # Check if the frequencies of elements in A and B match
    for num, freq in freqA.items():
        if num not in freqB or freqB[num] != freq:
            return False
 
    # If frequencies match, return true
    return True
 
# Main function
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)
        {
            // Create dictionaries to store the frequency of elements in A and B
            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;
                }
            }
 
            // Check if the frequencies of elements in A and B match
            foreach (var kvp in freqA)
            {
                if (!freqB.TryGetValue(kvp.Key, out int freqBValue) || freqBValue != kvp.Value)
                {
                    return false;
                }
            }
 
            // If frequencies match, return true
            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) {
    // Create objects to store the frequency of elements in A and B
    let freqA = {};
    let freqB = {};
 
    // Count the frequency of elements in arrays A and B
    for (let num of A) {
        freqA[num] = (freqA[num] || 0) + 1;
    }
    for (let num of B) {
        freqB[num] = (freqB[num] || 0) + 1;
    }
 
    // Check if the frequencies of elements in A and B match
    for (let num in freqA) {
        if (!freqB.hasOwnProperty(num) || freqB[num] !== freqA[num]) {
            return false;
        }
    }
 
    // If frequencies match, return true
    return true;
}
 
// Main function
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.



Next Article
Check if Arrays can be made equal by Replacing elements with their number of Digits
author
spp____
Improve
Article Tags :
  • Arrays
  • DSA
  • Sorting
  • anagram
  • Reverse
  • subarray
Practice Tags :
  • anagram
  • Arrays
  • Reverse
  • Sorting

Similar Reads

  • Check if two arrays can be made equal by reversing any subarray once
    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.
    8 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
  • 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
  • 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
  • Number of times an array can be partitioned repetitively into two subarrays with equal sum
    Given an array arr[] of size N, the task is to find the number of times the array can be partitioned repetitively into two subarrays such that the sum of the elements of both the subarrays is the same. Examples: Input: arr[] = { 2, 2, 2, 2 } Output: 3 Explanation: 1. Make the first partition after i
    8 min read
  • Check if an array can be split into K non-overlapping subarrays whose Bitwise AND values are equal
    Given an array arr[] of size N and a positive integer K, the task is to check if the array can be split into K non-overlapping and non-empty subarrays such that Bitwise AND of all the subarrays are equal. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: arr[] = { 3, 2,
    11 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 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 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 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
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