Check if two arrays are permutations of each other - GeeksQuiz
Given two unsorted arrays of same size, write a function that returns true if two arrays are permutations of each other, otherwise false.
http://www.algoqueue.com/algoqueue/default/view/3735552/check-if-two-arrays-are-permutation-of-each-other
Given two unsorted arrays of same size, write a function that returns true if two arrays are permutations of each other, otherwise false.
A Simple Solution is sort both arrays and compare sorted arrays. 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 element is found then decrement its count in hash map. If not found, then return false.
3) If all elements are found then return true.
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 element is found then decrement its count in hash map. If not found, then return false.
3) If all elements are found then return true.
// A Java program to find one array is permutation of other array import java.util.HashMap; class Permutaions { // Returns true if arr1[] and arr2[] are permutations of each other static Boolean arePermutations( int arr1[], int arr2[]) { // 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 ; } |
public boolean checkPermutation(int[] array1, int[] array2){ /* If two arrays have different length - not a permutation*/ if (array1.length !== array2.length) return false; /* Sort 1st array */ Arrays.sort(array1); /* Sort 2nd array */ Arrays.sort(array2); for(int i = 0; i < array1.length; i++){ if(array1[i] !== array2[i]) return false; } return true; }Read full article from Check if two arrays are permutations of each other - GeeksQuiz