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.
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 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.
Read full article from Check if two arrays are permutations of each other - GeeksQuiz
No comments:
Post a Comment