Check if two arrays are permutations of each other
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.
- Create a Hash Map for all the elements of arr1[] such that array elements are keys and their counts are values.
- 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.
- If all elements are found then return true.
Below is the implementation of this approach.
C++
#include <bits/stdc++.h>
using namespace std;
bool arePermutations( int arr1[], int arr2[], int n, int m)
{
if (n != m)
{
return false ;
}
unordered_map< int , int > hm;
for ( int i = 0; i < n; i++)
{
int x = arr1[i];
hm[x]++;
}
for ( int i = 0; i < m; i++)
{
int x = arr2[i];
if (hm[x] == 0)
{
return false ;
}
hm[x]--;
}
return true ;
}
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.HashMap;
class Permutations
{
static Boolean arePermutations( int arr1[], int arr2[])
{
if (arr1.length != arr2.length)
return false ;
HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>();
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 );
}
}
for ( int i = 0 ; i < arr2.length; i++)
{
int x = arr2[i];
if (hM.get(x) == null || hM.get(x) == 0 )
return false ;
int k = hM.get(x);
hM.put(x, k- 1 );
}
return true ;
}
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
from collections import defaultdict
def arePermutations(arr1, arr2):
if ( len (arr1) ! = len (arr2)):
return False
hM = defaultdict ( int )
for i in range ( len (arr1)):
x = arr1[i]
hM[x] + = 1
for i in range ( len (arr2)):
x = arr2[i]
if x not in hM or hM[x] = = 0 :
return False
hM[x] - = 1
return True
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" )
|
C#
using System;
using System.Collections.Generic;
public class Permutations {
static Boolean arePermutations( int [] arr1, int [] arr2)
{
if (arr1.Length != arr2.Length)
return false ;
Dictionary< int , int > hM = new Dictionary< int , int >();
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);
}
}
for ( int i = 0; i < arr2.Length; i++) {
int x = arr2[i];
if (!hM.ContainsKey(x))
return false ;
int k = hM[x];
if (k == 0)
return false ;
hM.Remove(x);
hM.Add(x, k - 1);
}
return true ;
}
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" );
}
}
|
Javascript
<script>
function arePermutations(arr1,arr2)
{
if (arr1.length != arr2.length)
return false ;
let hM = new 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);
}
}
for (let i = 0; i < arr2.length; i++)
{
let x = arr2[i];
if (!hM.has(x) || hM[x] == 0)
return false ;
let k = hM[x];
hM.set(x, k-1);
}
return true ;
}
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"
);
</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;
bool arePermutations( int arr1[], int arr2[], int n, int m)
{
if (n != m)
{
return false ;
}
sort(arr1, arr1 + n);
sort(arr2, arr2 + m);
for ( int i = 0; i < n; i++)
{
if (arr1[i] != arr2[i])
{
return false ;
}
}
return true ;
}
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) {
if (n != m) {
return false ;
}
Arrays.sort(arr1);
Arrays.sort(arr2);
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):
n = len (arr1)
m = len (arr2)
if n ! = m:
return False
arr1.sort()
arr2.sort()
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) {
int n = arr1.Length;
int m = arr2.Length;
if (n != m) {
return false ;
}
Array.Sort(arr1);
Array.Sort(arr2);
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) {
const n = arr1.length;
const m = arr2.length;
if (n !== m) {
return false ;
}
arr1.sort();
arr2.sort();
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
- 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.
- 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.
- 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.
- 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.
- The arePermutations function is the entry point of the algorithm. It takes the two arrays arr1 and arr2 as input.
- 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.
- Next, we initialize a boolean visited array with false values to keep track of the used elements in arr2.
- We then call the dfs function, passing in arr1, arr2, visited, and the starting index of 0.
- If the dfs function returns true, it means a permutation has been found, so we return true from the arePermutations function as well.
- 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;
bool dfs(vector< int >& arr1, vector< int >& arr2, vector< bool >& visited,
int index) {
if (index == arr1.size()) {
return true ;
}
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 ;
}
}
return false ;
}
bool arePermutations(vector< int >& arr1, vector< int >& arr2) {
int n = arr1.size();
int m = arr2.size();
if (n != m) {
return false ;
}
vector< bool > visited(m, false );
return dfs(arr1, arr2, visited, 0);
}
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 {
private static boolean dfs(List<Integer> arr1, List<Integer> arr2,
boolean [] visited, int index) {
if (index == arr1.size()) {
return true ;
}
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 ;
}
}
return false ;
}
private static boolean arePermutations(List<Integer> arr1,
List<Integer> arr2) {
int n = arr1.size();
int m = arr2.size();
if (n != m) {
return false ;
}
boolean [] visited = new boolean [m];
return dfs(arr1, arr2, visited, 0 );
}
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
def dfs(arr1, arr2, visited, index):
if index = = len (arr1):
return True
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
return False
def arePermutations(arr1, arr2):
n = len (arr1)
m = len (arr2)
if n ! = m:
return False
visited = [ False ] * m
return dfs(arr1, arr2, visited, 0 )
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" )
|
C#
using System;
using System.Collections.Generic;
class GFG {
static bool DFS(List< int > arr1, List< int > arr2,
bool [] visited, int index)
{
if (index == arr1.Count) {
return true ;
}
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 ;
}
}
return false ;
}
static bool ArePermutations(List< int > arr1,
List< int > arr2)
{
int n = arr1.Count;
int m = arr2.Count;
if (n != m) {
return false ;
}
bool [] visited = new bool [m];
return DFS(arr1, arr2, visited, 0);
}
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
function dfs(arr1, arr2, visited, index) {
if (index === arr1.length) {
return true ;
}
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 ;
}
}
return false ;
}
function arePermutations(arr1, arr2) {
const n = arr1.length;
const m = arr2.length;
if (n !== m) {
return false ;
}
const visited = new Array(m).fill( false );
return dfs(arr1, arr2, visited, 0);
}
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 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
Share your thoughts in the comments
Please Login to comment...