Given two arrays a[] and b[] of equal size, the task is to find whether the given arrays are permutation of each other. Two arrays are said to be permutation if both contain the same set of elements, arrangements of elements may be different though.
Note: If there are repetitions, then counts of repeated elements must also be the same for two arrays to be permutation.
Examples:Â
Input: a[] = [1, 2, 5, 4, 0], b[] = [2, 4, 5, 0, 1]
Output: true
Explanation: Both arrays contain the same elements and can be rearranged to [0, 1, 2, 4, 5]. Therefore, the output is true.Input: a[] = [1, 2, 5], b[] = [2, 4, 15]
Output: false
Explanation: a[] and b[] have only one common value, 2. All others elements are different so the arrays cannot be rearranged to become equal. Therefore, the output is false.
Table of Content
[Naive Approach] Sorting - O(n*log n) Time and O(1) Space
The idea is to sort both arrays and then compare their elements one by one. If all corresponding elements are equal, both arrays contain the same elements with the same frequencies.
- If the array sizes are different, return false.
- Sort both arrays.
- Compare corresponding elements of both arrays.
- If any elements differ, return false.
- If all elements match, return true.
#include <bits/stdc++.h>
using namespace std;
// Check whether two arrays contain the same elements
// with the same frequencies.
bool checkPermutation(vector<int> &a, vector<int> &b)
{
int n = a.size();
int m = b.size();
// Arrays with different sizes cannot be equal.
if (n!= m)
return false;
// Sort both arrays so that equal elements
// appear at the same positions.
sort(a.begin(), a.end());
sort(b.begin(), b.end());
// Compare elements at each position.
for (int i = 0; i < n; i++)
{
if (a[i]!= b[i])
return false;
}
// All elements and their frequencies are equal.
return true;
}
int main()
{
vector<int> a = {3, 5, 2, 5, 2};
vector<int> b = {2, 3, 5, 5, 2};
if (checkPermutation(a, b))
cout << "true";
else
cout << "false";
return 0;
}
import java.util.*;
class GFG {
static boolean checkPermutation(int[] a, int[] b)
{
int n = a.length;
int m = b.length;
// Arrays with different sizes cannot be permutations.
if (n!= m)
return false;
// Sort both arrays so that equal elements
// appear at the same positions.
Arrays.sort(a);
Arrays.sort(b);
// Compare elements at each position.
for (int i = 0; i < n; i++) {
if (a[i]!= b[i])
return false;
}
// All elements and their frequencies are equal.
return true;
}
public static void main(String[] args)
{
int[] a = { 3, 5, 2, 5, 2 };
int[] b = { 2, 3, 5, 5, 2 };
if (checkPermutation(a, b))
System.out.println("true");
else
System.out.println("false");
}
}
import json
# Check whether two arrays contain the same elements
# with the same frequencies.
def checkPermutation(a, b):
n = len(a)
m = len(b)
# Arrays with different sizes cannot be equal.
if n!= m:
return False
# Sort both arrays so that equal elements
# appear at the same positions.
a.sort()
b.sort()
# Compare elements at each position.
for i in range(n):
if a[i]!= b[i]:
return False
# All elements and their frequencies are equal.
return True
# Driver Code
if __name__ == "__main__":
a = [3, 5, 2, 5, 2]
b = [2, 3, 5, 5, 2]
if checkPermutation(a, b):
print("true")
else:
print("false")
using System;
class GFG {
static bool checkPermutation(int[] a, int[] b)
{
int n = a.Length;
int m = b.Length;
// Arrays with different sizes cannot be equal.
if (n!= m)
return false;
// Sort both arrays so that equal elements
// appear at the same positions.
Array.Sort(a);
Array.Sort(b);
// Compare elements at each position.
for (int i = 0; i < n; i++) {
if (a[i]!= b[i])
return false;
}
// All elements and their frequencies are equal.
return true;
}
static void Main()
{
int[] a = { 3, 5, 2, 5, 2 };
int[] b = { 2, 3, 5, 5, 2 };
if (checkPermutation(a, b))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
// Check whether two arrays contain the same elements
// with the same frequencies.
function checkPermutation(a, b)
{
let n = a.length;
let m = b.length;
// Arrays with different sizes cannot be equal.
if (n!== m)
return false;
// Sort both arrays so that equal elements
// appear at the same positions.
a.sort((x, y) => x - y);
b.sort((x, y) => x - y);
// Compare elements at each position.
for (let i = 0; i < n; i++) {
if (a[i]!== b[i])
return false;
}
// All elements and their frequencies are equal.
return true;
}
// Driver Code
let a = [ 3, 5, 2, 5, 2 ];
let b = [ 2, 3, 5, 5, 2 ];
if (checkPermutation(a, b))
console.log("true");
else
console.log("false");
Output
true
[Expected Approach] Hashing- O(n)Â Time and O(n) Space
The idea is to use a frequency map to count how many times each element occurs in the first array.
Then, reduce the count for each element in the second array and check whether all required frequencies are available.
- If the array sizes are different, return false.
- Store the frequency of each element of the first array.
- Traverse the second array and check whether each element is available.
- Decrease its frequency after using it.
- If any frequency becomes unavailable, return false.
- If all elements are matched, return true.
#include <bits/stdc++.h>
using namespace std;
// Check whether two arrays contain the same elements
// with the same frequencies.
bool checkPermutation(vector<int> &a, vector<int> &b)
{
int n = a.size();
int m = b.size();
// Arrays with different sizes cannot be equal.
if (n!= m)
return false;
// Store the frequency of each element in the first array.
unordered_map<int, int> freq;
for (int i = 0; i < n; i++)
freq[a[i]]++;
// Check each element of the second array.
for (int i = 0; i < n; i++)
{
// Element does not exist in the first array.
if (freq.find(b[i]) == freq.end())
return false;
// Element occurs more times in the second array
// than it does in the first array.
if (freq[b[i]] == 0)
return false;
// Use one occurrence of this element.
freq[b[i]]--;
}
// All elements and their frequencies match.
return true;
}
int main()
{
vector<int> a = {3, 5, 2, 5, 2};
vector<int> b = {2, 3, 5, 5, 2};
if (checkPermutation(a, b))
cout << "true";
else
cout << "false";
return 0;
}
import java.util.*;
class GFG {
static boolean checkPermutation(int[] a, int[] b)
{
int n = a.length;
int m = b.length;
// Arrays with different sizes cannot be equal.
if (n!= m)
return false;
// Store the frequency of each element in the first
// array.
HashMap<Integer, Integer> freq = new HashMap<>();
for (int i = 0; i < n; i++)
freq.put(a[i], freq.getOrDefault(a[i], 0) + 1);
// Check each element of the second array.
for (int i = 0; i < n; i++) {
// Element does not exist in the first array.
if (!freq.containsKey(b[i]))
return false;
// Element occurs more times in the second array
// than it does in the first array.
if (freq.get(b[i]) == 0)
return false;
// Use one occurrence of this element.
freq.put(b[i], freq.get(b[i]) - 1);
}
// All elements and their frequencies match.
return true;
}
public static void main(String[] args)
{
int[] a = { 3, 5, 2, 5, 2 };
int[] b = { 2, 3, 5, 5, 2 };
if (checkPermutation(a, b))
System.out.println("true");
else
System.out.println("false");
}
}
def checkPermutation(a, b):
n = len(a)
m = len(b)
# Arrays with different sizes cannot be equal.
if n!= m:
return False
# Store the frequency of each element in the first array.
freq = {}
for i in range(n):
freq[a[i]] = freq.get(a[i], 0) + 1
# Check each element of the second array.
for i in range(n):
# Element does not exist in the first array.
if b[i] not in freq:
return False
# Element occurs more times in the second array
# than it does in the first array.
if freq[b[i]] == 0:
return False
# Use one occurrence of this element.
freq[b[i]] -= 1
# All elements and their frequencies match.
return True
# Driver Code
if __name__ == "__main__":
a = [3, 5, 2, 5, 2]
b = [2, 3, 5, 5, 2]
if checkPermutation(a, b):
print("true")
else:
print("false")
using System;
using System.Collections.Generic;
class GFG {
static bool checkPermutation(int[] a, int[] b)
{
int n = a.Length;
int m = b.Length;
// Arrays with different sizes cannot be equal.
if (n!= m)
return false;
// Store the frequency of each element in the first
// array.
Dictionary<int, int> freq
= new Dictionary<int, int>();
for (int i = 0; i < n; i++) {
if (!freq.ContainsKey(a[i]))
freq[a[i]] = 0;
freq[a[i]]++;
}
// Check each element of the second array.
for (int i = 0; i < n; i++) {
// Element does not exist in the first array.
if (!freq.ContainsKey(b[i]))
return false;
// Element occurs more times in the second array
// than it does in the first array.
if (freq[b[i]] == 0)
return false;
// Use one occurrence of this element.
freq[b[i]]--;
}
// All elements and their frequencies match.
return true;
}
static void Main()
{
int[] a = { 3, 5, 2, 5, 2 };
int[] b = { 2, 3, 5, 5, 2 };
if (checkPermutation(a, b))
Console.WriteLine("true");
else
Console.WriteLine("false");
}
}
// Check whether two arrays contain the same elements
// with the same frequencies.
function checkPermutation(a, b)
{
let n = a.length;
let m = b.length;
// Arrays with different sizes cannot be equal.
if (n!== m)
return false;
// Store the frequency of each element in the first
// array.
let freq = new Map();
for (let i = 0; i < n; i++) {
freq.set(a[i], (freq.get(a[i]) || 0) + 1);
}
// Check each element of the second array.
for (let i = 0; i < n; i++) {
// Element does not exist in the first array.
if (!freq.has(b[i]))
return false;
// Element occurs more times in the second array
// than it does in the first array.
if (freq.get(b[i]) === 0)
return false;
// Use one occurrence of this element.
freq.set(b[i], freq.get(b[i]) - 1);
}
// All elements and their frequencies match.
return true;
}
// Driver Code
let a = [ 3, 5, 2, 5, 2 ];
let b = [ 2, 3, 5, 5, 2 ];
if (checkPermutation(a, b))
console.log("true");
else
console.log("false");
Output
true