Open In App
Related Articles

Check if two arrays are permutations of each other

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given two unsorted arrays of the same size, write a function that returns true if two arrays are permutations of each other, otherwise false.

Examples: 

Input: arr1[] = {2, 1, 3, 5, 4, 3, 2}
arr2[] = {3, 2, 2, 4, 5, 3, 1}
Output: Yes
Input: arr1[] = {2, 1, 3, 5,}
arr2[] = {3, 2, 2, 4}
Output: No

We strongly recommend you to minimize your browser and try this yourself first.
A Simple Solution is to sort both arrays and compare sorted arrays. The time complexity of this solution is O(nLogn)
A Better Solution is to use Hashing

  1. Create a Hash Map for all the elements of arr1[] such that array elements are keys and their counts are values.
  2. Traverse arr2[] and search for each element of arr2[] in the Hash Map. If an element is found then decrement its count in the hash map. If not found, then return false.
  3. If all elements are found then return true.

Below is the implementation of this approach.  

C++

// A C++ program to find one array is permutation of other array
#include <bits/stdc++.h>
using namespace std;
 
// Returns true if arr1[] and arr2[] are permutations of each other
bool arePermutations(int arr1[], int arr2[], int n, int m)
{
     
    // Arrays cannot be permutations of one another unless they are
    // of the same length
    if(n != m)
    {
        return false;
    }
   
    // Creates an empty hashMap hM
    unordered_map<int, int> hm;
     
    // Traverse through the first array and add elements to hash map
    for (int i = 0; i < n; i++)
    {
        int x = arr1[i];
        hm[x]++;
    }
     
    // Traverse through second array and check if every element is
    // present in hash map
    for (int i = 0; i < m; i++)
    {
        int x = arr2[i];
       
        // If element is not present in hash map or element
        // is not present less number of times
        if(hm[x] == 0)
        {
            return false;
        }
        hm[x]--;
    }
    return true;
}
 
// Driver function to test above function
int main() {
    int arr1[] = {2, 1, 3, 5, 4, 3, 2};
    int arr2[] = {3, 2, 2, 4, 5, 3, 1};
    int n = sizeof(arr1)/sizeof(arr1[0]);
    int m = sizeof(arr2)/sizeof(arr2[0]);
    if (arePermutations(arr1, arr2, n, m))
        cout << "Arrays are permutations of each other" << endl;
    else
        cout << "Arrays are NOT permutations of each other" << endl;
     
    return 0;
}
 
// This code is contributed by avanitrachhadiya2155

                    

Java

// A Java program to find one array is permutation of other array
import java.util.HashMap;
 
class Permutations
{
    // Returns true if arr1[] and arr2[] are permutations of each other
    static Boolean arePermutations(int arr1[], int arr2[])
    {
        // Arrays cannot be permutations of one another unless they are
        // of the same length
        if (arr1.length != arr2.length)
            return false;
       
        // Creates an empty hashMap hM
        HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>();
 
        // Traverse through the first array and add elements to hash map
        for (int i = 0; i < arr1.length; i++)
        {
            int x = arr1[i];
            if (hM.get(x) == null)
                hM.put(x, 1);
            else
            {
                int k = hM.get(x);
                hM.put(x, k+1);
            }
        }
 
        // Traverse through second array and check if every element is
        // present in hash map
        for (int i = 0; i < arr2.length; i++)
        {
            int x = arr2[i];
 
            // If element is not present in hash map or element
            // is not present less number of times
            if (hM.get(x) == null || hM.get(x) == 0)
                return false;
 
            int k = hM.get(x);
            hM.put(x, k-1);
        }
        return true;
    }
 
    // Driver function to test above function
    public static void main(String arg[])
    {
        int arr1[] = {2, 1, 3, 5, 4, 3, 2};
        int arr2[] = {3, 2, 2, 4, 5, 3, 1};
        if (arePermutations(arr1, arr2))
            System.out.println("Arrays are permutations of each other");
        else
            System.out.println("Arrays are NOT permutations of each other");
    }
}

                    

Python3

# Python3 program to find one
# array is permutation of other array
from collections import defaultdict
 
# Returns true if arr1[] and
# arr2[] are permutations of
# each other
def arePermutations(arr1, arr2):
    # Arrays cannot be permutations of one another
    # unless they are of the same length
    if (len(arr1) != len(arr2)):
        return False
       
    # Creates an empty hashMap hM
    hM = defaultdict (int)
 
    # Traverse through the first
    # array and add elements to
    # hash map
    for i in range (len(arr1)):
         
        x = arr1[i]
        hM[x] += 1
         
    # Traverse through second array
    # and check if every element is
    # present in hash map
    for i in range (len(arr2)):
        x = arr2[i]
 
        # If element is not present
        # in hash map or element
        # is not present less number
        # of times
        if x not in hM or hM[x] == 0:
             return False
 
        hM[x] -= 1
        
    return True
 
# Driver code
if __name__ == "__main__":
   
    arr1 = [2, 1, 3, 5, 4, 3, 2]
    arr2 = [3, 2, 2, 4, 5, 3, 1]
    if (arePermutations(arr1, arr2)):
        print("Arrays are permutations of each other")
    else:
        print("Arrays are NOT permutations of each other")
         
# This code is contributed by Chitranayal

                    

C#

// C# program to find one array
// is permutation of other array
using System;
using System.Collections.Generic;
 
public class Permutations {
    // Returns true if arr1[] and arr2[]
    // are permutations of each other
    static Boolean arePermutations(int[] arr1, int[] arr2)
    {
        // Arrays cannot be permutations of one another if
        // they are not the same length
        if (arr1.Length != arr2.Length)
            return false;
 
        // Creates an empty hashMap hM
        Dictionary<int, int> hM = new Dictionary<int, int>();
 
        // Traverse through the first array
        // and add elements to hash map
        for (int i = 0; i < arr1.Length; i++) {
            int x = arr1[i];
            if (!hM.ContainsKey(x))
                hM.Add(x, 1);
            else {
                int k = hM[x];
                hM.Remove(x);
                hM.Add(x, k + 1);
            }
        }
 
        // Traverse through second array and check if every
        // element is present in hash map (and the same
        // number of times)
        for (int i = 0; i < arr2.Length; i++) {
            int x = arr2[i];
 
            // If element is not present in hash map or
            // element is not present the same number of
            // times
            if (!hM.ContainsKey(x))
                return false; // Not present in the hash map
 
            int k = hM[x];
            if (k == 0)
                return false; // Not present the same number
                              // of times
            hM.Remove(x);
            hM.Add(x, k - 1);
        }
        return true;
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr1 = { 2, 1, 3, 5, 4, 3, 2 };
        int[] arr2 = { 3, 2, 2, 4, 5, 3, 1 };
        if (arePermutations(arr1, arr2))
            Console.WriteLine("Arrays are permutations of each other");
        else
            Console.WriteLine("Arrays are NOT permutations of each other");
    }
}
 
/* This code contributed by PrinciRaj1992 */

                    

Javascript

<script>
 
// A Javascript program to find one array
/// is permutation of other array
     
    // Returns true if arr1[] and arr2[]
    // are permutations of each other
    function arePermutations(arr1,arr2)
    {
        // Arrays cannot be permutations of
        // one another unless they are
        // of the same length
        if (arr1.length != arr2.length)
            return false;
        
        // Creates an empty hashMap hM
        let hM = new Map();
  
        // Traverse through the first array
        // and add elements to hash map
        for (let i = 0; i < arr1.length; i++)
        {
            let x = arr1[i];
            if (!hM.has(x))
                hM.set(x, 1);
            else
            {
                let k = hM[x];
                hM.set(x, k+1);
            }
        }
  
        // Traverse through second array and
        // check if every element is
        // present in hash map
        for (let i = 0; i < arr2.length; i++)
        {
            let x = arr2[i];
  
            // If element is not present in
            // hash map or element
            // is not present less number of times
            if (!hM.has(x) || hM[x] == 0)
                return false;
  
            let k = hM[x];
            hM.set(x, k-1);
        }
        return true;
    }
     
    // Driver function to test above function
    let arr1=[2, 1, 3, 5, 4, 3, 2];
    let arr2=[3, 2, 2, 4, 5, 3, 1];
    if (arePermutations(arr1, arr2))
        document.write(
        "Arrays are permutations of each other"
        );
    else
        document.write(
        "Arrays are NOT permutations of each other"
        );
     
    // This code is contributed by rag2127
     
</script>

                    

Output
Arrays are permutations of each other







Time complexity: O(n) under the assumption that we have a hash function that inserts and finds elements in O(1) time.
Auxiliary space: O(n) because it is using map

Approach 2: No Extra Space:

Another approach to check if one array is a permutation of another array is to sort both arrays and then compare each element of both arrays. If all the elements are the same in both arrays, then they are permutations of each other. Note that the space complexity will be optimized since it does not require any extra data structure to store values.

Here’s the code for this approach:

C++

#include <bits/stdc++.h>
using namespace std;
 
// Returns true if arr1[] and arr2[] are permutations of each other
bool arePermutations(int arr1[], int arr2[], int n, int m)
{
    // Arrays cannot be permutations of one another unless they are
    // of the same length
    if (n != m)
    {
        return false;
    }
 
    // Sort both arrays
    sort(arr1, arr1 + n);
    sort(arr2, arr2 + m);
 
    // Compare each element of both arrays
    for (int i = 0; i < n; i++)
    {
        if (arr1[i] != arr2[i])
        {
            return false;
        }
    }
 
    return true;
}
 
// Driver function to test above function
int main()
{
    int arr1[] = {2, 1, 3, 5, 4, 3, 2};
    int arr2[] = {3, 2, 2, 4, 5, 3, 1};
    int n = sizeof(arr1) / sizeof(arr1[0]);
    int m = sizeof(arr2) / sizeof(arr2[0]);
 
    if (arePermutations(arr1, arr2, n, m))
    {
        cout << "Arrays are permutations of each other" << endl;
    }
    else
    {
        cout << "Arrays are NOT permutations of each other" << endl;
    }
 
    return 0;
}

                    

Java

import java.util.Arrays;
 
public class PermutationChecker {
    public static boolean arePermutations(int[] arr1, int[] arr2, int n, int m) {
        // Arrays cannot be permutations of one another unless they are
        // of the same length
        if (n != m) {
            return false;
        }
 
        // Sort both arrays
        Arrays.sort(arr1);
        Arrays.sort(arr2);
 
        // Compare each element of both arrays
        for (int i = 0; i < n; i++) {
            if (arr1[i] != arr2[i]) {
                return false;
            }
        }
 
        return true;
    }
 
    public static void main(String[] args) {
        int[] arr1 = {2, 1, 3, 5, 4, 3, 2};
        int[] arr2 = {3, 2, 2, 4, 5, 3, 1};
        int n = arr1.length;
        int m = arr2.length;
 
        if (arePermutations(arr1, arr2, n, m)) {
            System.out.println("Arrays are permutations of each other");
        } else {
            System.out.println("Arrays are NOT permutations of each other");
        }
    }
}

                    

Python3

def are_permutations(arr1, arr2):
    # Arrays cannot be permutations of one another unless they are
    # of the same length
    n = len(arr1)
    m = len(arr2)
    if n != m:
        return False
     
    # Sort both arrays
    arr1.sort()
    arr2.sort()
     
    # Compare each element of both arrays
    for i in range(n):
        if arr1[i] != arr2[i]:
            return False
     
    return True
 
arr1 = [2, 1, 3, 5, 4, 3, 2]
arr2 = [3, 2, 2, 4, 5, 3, 1]
 
if are_permutations(arr1, arr2):
    print("Arrays are permutations of each other")
else:
    print("Arrays are NOT permutations of each other")

                    

C#

using System;
 
class PermutationChecker {
    static bool ArePermutations(int[] arr1, int[] arr2) {
        // Arrays cannot be permutations of one another unless they are
        // of the same length
        int n = arr1.Length;
        int m = arr2.Length;
        if (n != m) {
            return false;
        }
         
        // Sort both arrays
        Array.Sort(arr1);
        Array.Sort(arr2);
         
        // Compare each element of both arrays
        for (int i = 0; i < n; i++) {
            if (arr1[i] != arr2[i]) {
                return false;
            }
        }
         
        return true;
    }
 
    static void Main() {
        int[] arr1 = {2, 1, 3, 5, 4, 3, 2};
        int[] arr2 = {3, 2, 2, 4, 5, 3, 1};
 
        if (ArePermutations(arr1, arr2)) {
            Console.WriteLine("Arrays are permutations of each other");
        } else {
            Console.WriteLine("Arrays are NOT permutations of each other");
        }
    }
}

                    

Javascript

function arePermutations(arr1, arr2) {
  // Arrays cannot be permutations of one another unless they are
  // of the same length
  const n = arr1.length;
  const m = arr2.length;
  if (n !== m) {
    return false;
  }
 
  // Sort both arrays
  arr1.sort();
  arr2.sort();
 
  // Compare each element of both arrays
  for (let i = 0; i < n; i++) {
    if (arr1[i] !== arr2[i]) {
      return false;
    }
  }
 
  return true;
}
 
const arr1 = [2, 1, 3, 5, 4, 3, 2];
const arr2 = [3, 2, 2, 4, 5, 3, 1];
 
if (arePermutations(arr1, arr2)) {
  console.log("Arrays are permutations of each other");
} else {
  console.log("Arrays are NOT permutations of each other");
}

                    

Output
Arrays are permutations of each other







Time complexity: O(N*log(N)), Where N is the size of the arrays
Auxiliary space: O(1) 

Approach: Using DFS

  1. We start by defining a helper function called dfs that performs the DFS traversal. This function takes the following parameters:       
  • arr1 and arr2: The two arrays we want to check for permutations.
  • visited: A boolean array to keep track of the elements in arr2 that have been used.
  • index: The current index in arr1 that we are matching.
  1. The base case of the DFS function is when we have checked all elements in arr1. If the index reaches the length of arr1, it means we have successfully matched all elements, so we return true.
  2. For the current element in arr1 at index index, we iterate over arr2 to find a matching element that hasn’t been used before. If we find a match, we mark the element in arr2 as visited and recursively call dfs with the next index.
  3. If the recursive call returns true, it means a permutation has been found, so we return true from the current call as well. Otherwise, we backtrack by marking the element in arr2 as not visited and continue searching for other permutations.
  4. The arePermutations function is the entry point of the algorithm. It takes the two arrays arr1 and arr2 as input.
  5. First, we check if the lengths of the arrays arr1 and arr2 are different. If they are not equal, the arrays cannot be permutations of each other, so we return false.
  6. Next, we initialize a boolean visited array with false values to keep track of the used elements in arr2.
  7. We then call the dfs function, passing in arr1, arr2, visited, and the starting index of 0.
  8. If the dfs function returns true, it means a permutation has been found, so we return true from the arePermutations function as well.
  9. If no permutation is found after the DFS traversal, we return false.

By using DFS, the modified code explores all possible paths in the search space, which corresponds to the different permutations of the arrays. The backtracking step allows the algorithm to efficiently search for permutations by avoiding unnecessary exploration of paths that cannot lead to valid permutations.

C++

#include <bits/stdc++.h>
using namespace std;
 
// Helper function to perform DFS
bool dfs(vector<int>& arr1, vector<int>& arr2, vector<bool>& visited,
         int index) {
    // Base case: All elements have been visited
    if (index == arr1.size()) {
        return true;
    }
 
    // Check if the current element in arr1 has a
   // corresponding element in arr2
    int num = arr1[index];
    for (int i = 0; i < arr2.size(); i++) {
        if (!visited[i] && arr2[i] == num) {
            visited[i] = true;
            if (dfs(arr1, arr2, visited, index + 1)) {
                return true;
            }
            visited[i] = false; // Backtrack
        }
    }
 
    return false;
}
 
// Returns true if arr1[] and arr2[] are permutations of each other
bool arePermutations(vector<int>& arr1, vector<int>& arr2) {
    int n = arr1.size();
    int m = arr2.size();
 
    // Arrays cannot be permutations of one another unless
   // they are of the same length
    if (n != m) {
        return false;
    }
 
    // Initialize a visited array to keep track of used elements
   // in arr2
    vector<bool> visited(m, false);
 
    // Perform DFS to check for permutations
    return dfs(arr1, arr2, visited, 0);
}
 
// Driver function to test above function
int main() {
    vector<int> arr1 = {2, 1, 3, 5, 4, 3, 2};
    vector<int> arr2 = {3, 2, 2, 4, 5, 3, 1};
 
    if (arePermutations(arr1, arr2)) {
        cout << "Arrays are permutations of each other" << endl;
    } else {
        cout << "Arrays are NOT permutations of each other" << endl;
    }
 
    return 0;
}

                    

Java

import java.util.ArrayList;
import java.util.List;
 
public class GFG {
 
    // Helper function to perform DFS
    private static boolean dfs(List<Integer> arr1, List<Integer> arr2,
                               boolean[] visited, int index) {
        // Base case: All elements have been visited
        if (index == arr1.size()) {
            return true;
        }
 
        // Check if the current element in arr1 has a
       // corresponding element in arr2
        int num = arr1.get(index);
        for (int i = 0; i < arr2.size(); i++) {
            if (!visited[i] && arr2.get(i) == num) {
                visited[i] = true;
                if (dfs(arr1, arr2, visited, index + 1)) {
                    return true;
                }
                visited[i] = false; // Backtrack
            }
        }
 
        return false;
    }
 
    // Returns true if arr1[] and arr2[] are permutations of
   // each other
    private static boolean arePermutations(List<Integer> arr1,
                                           List<Integer> arr2) {
        int n = arr1.size();
        int m = arr2.size();
 
        // Arrays cannot be permutations of one another
       // unless they are of the same length
        if (n != m) {
            return false;
        }
 
        // Initialize a visited array to keep track of used
       // elements in arr2
        boolean[] visited = new boolean[m];
 
        // Perform DFS to check for permutations
        return dfs(arr1, arr2, visited, 0);
    }
 
    // Driver function to test above function
    public static void main(String[] args) {
        List<Integer> arr1 = new ArrayList<>();
        arr1.add(2);
        arr1.add(1);
        arr1.add(3);
        arr1.add(5);
        arr1.add(4);
        arr1.add(3);
        arr1.add(2);
 
        List<Integer> arr2 = new ArrayList<>();
        arr2.add(3);
        arr2.add(2);
        arr2.add(2);
        arr2.add(4);
        arr2.add(5);
        arr2.add(3);
        arr2.add(1);
 
        if (arePermutations(arr1, arr2)) {
            System.out.println("Arrays are permutations of each other");
        } else {
            System.out.println("Arrays are NOT permutations of each other");
        }
    }
}

                    

Python3

# Helper function to perform DFS
def dfs(arr1, arr2, visited, index):
    # Base case: All elements have been visited
    if index == len(arr1):
        return True
 
    # Check if the current element in arr1 has a corresponding element in arr2
    num = arr1[index]
    for i in range(len(arr2)):
        if not visited[i] and arr2[i] == num:
            visited[i] = True
            if dfs(arr1, arr2, visited, index + 1):
                return True
            visited[i] = False  # Backtrack
 
    return False
 
# Returns true if arr1[] and arr2[] are permutations of each other
def arePermutations(arr1, arr2):
    n = len(arr1)
    m = len(arr2)
 
    # Lists cannot be permutations of one another unless they are of the same length
    if n != m:
        return False
 
    # Initialize a visited list to keep track of used elements in arr2
    visited = [False] * m
 
    # Perform DFS to check for permutations
    return dfs(arr1, arr2, visited, 0)
 
# Driver function to test above function
if __name__ == "__main__":
    arr1 = [2, 1, 3, 5, 4, 3, 2]
    arr2 = [3, 2, 2, 4, 5, 3, 1]
 
    if arePermutations(arr1, arr2):
        print("Arrays are permutations of each other")
    else:
        print("Arrays are NOT permutations of each other")
         
# This code is contributed by shivamgupta310570

                    

C#

using System;
using System.Collections.Generic;
 
class GFG {
    // Helper function to perform DFS
    static bool DFS(List<int> arr1, List<int> arr2,
                    bool[] visited, int index)
    {
        // Base case: All elements have been visited
        if (index == arr1.Count) {
            return true;
        }
 
        // Check if the current element in arr1 has a
        // corresponding element in arr2
        int num = arr1[index];
        for (int i = 0; i < arr2.Count; i++) {
            if (!visited[i] && arr2[i] == num) {
                visited[i] = true;
                if (DFS(arr1, arr2, visited, index + 1)) {
                    return true;
                }
                visited[i] = false; // Backtrack
            }
        }
 
        return false;
    }
 
    // Returns true if arr1[] and arr2[] are permutations of
    // each other
    static bool ArePermutations(List<int> arr1,
                                List<int> arr2)
    {
        int n = arr1.Count;
        int m = arr2.Count;
 
        // Arrays cannot be permutations of one another
        // unless they are of the same length
        if (n != m) {
            return false;
        }
 
        // Initialize a visited array to keep track of used
        // elements in arr2
        bool[] visited = new bool[m];
 
        // Perform DFS to check for permutations
        return DFS(arr1, arr2, visited, 0);
    }
 
    // Driver function to test the above function
    static void Main()
    {
        List<int> arr1
            = new List<int>{ 2, 1, 3, 5, 4, 3, 2 };
        List<int> arr2
            = new List<int>{ 3, 2, 2, 4, 5, 3, 1 };
 
        if (ArePermutations(arr1, arr2)) {
            Console.WriteLine(
                "Arrays are permutations of each other");
        }
        else {
            Console.WriteLine(
                "Arrays are NOT permutations of each other");
        }
    }
}

                    

Javascript

// JavaScript Program for the above approach
function dfs(arr1, arr2, visited, index) {
  // Base case: All elements have been visited
  if (index === arr1.length) {
    return true;
  }
 
  // Check if the current element in arr1 has a corresponding
  // element in arr2
  const num = arr1[index];
  for (let i = 0; i < arr2.length; i++) {
    if (!visited[i] && arr2[i] === num) {
      visited[i] = true;
      if (dfs(arr1, arr2, visited, index + 1)) {
        return true;
      }
      visited[i] = false; // Backtrack
    }
  }
 
  return false;
}
 
function arePermutations(arr1, arr2) {
  const n = arr1.length;
  const m = arr2.length;
 
  // Arrays cannot be permutations of one another unless they
  // are of the same length
  if (n !== m) {
    return false;
  }
 
  // Initialize a visited array to keep track of used elements in arr2
  const visited = new Array(m).fill(false);
 
  // Perform DFS to check for permutations
  return dfs(arr1, arr2, visited, 0);
}
 
// Driver function to test above function
const arr1 = [2, 1, 3, 5, 4, 3, 2];
const arr2 = [3, 2, 2, 4, 5, 3, 1];
 
if (arePermutations(arr1, arr2)) {
    console.log("Arrays are permutations of each other");
} else {
    console.log("Arrays are NOT permutations of each other");
}
 
// THIS CODE IS CONTRIBUTED BY PIYUSH AGARWAL

                    

Output
Arrays are permutations of each other








Time complexity: O(n log n) ,where n is the length of the arrays. 

Auxiliary space: O(n), where n is the length of the arrays. 



Last Updated : 25 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads