Check if given two Arrays are equal (using Map)
Given two arrays, A and B, the task is to check if they are equal or not. Arrays are considered equal if any permutation of array B equates to array A.
Input: A = [2, 4, 5, 7, 5, 6] and B = [4, 2, 5, 5, 6, 7]
Explanation: All the elements in array A are present in array B and same number of times.
Input: A = [2, 5, 8, 9, 78] and B = [5, 2, 7, 78, 8]
Explanation: In array A there is a 9 and in array B there is a 7
Approach: The problem can be solved using hashmap based on the below idea:
Two arrays will be equal only if the frequency of the respective elements in both arrays are equal.
Follow the steps to solve the problem:
- If the sizes of both arrays are not equal, return NO.
- Maintain a hashmap and count the frequency of both the array elements
- If for any element the frequency is not the same, then return NO
- Otherwise, return YES
Below is the implementation of the above approach.
Time complexity: O(N) in average case and O(N2) in worst case.
Auxiliary Space: O(N)