Given two arrays arr1[] and arr2[] of size N and M respectively, the duty is to verify if the 2 arrays are equal or not.
Be aware: Arrays are mentioned to be equal if and provided that each arrays include the identical parts and the frequencies of every ingredient in each arrays are the identical.
Examples:
Enter: arr1[] = {1, 2, 3, 4, 5}, arr2[] = {5, 4, 3, 2, 1}
Output : Equal
Rationalization: As each the arrays include identical parts.Enter: arr1[] = {1, 5, 2, 7, 3, 8}, arr2[] = {8, 2, 3, 5, 7, 1}
Output : Equal
Naive Method: The essential technique to resolve the issue is as follows:
Apply sorting on each the arrays after which match every ingredient of 1 array with the ingredient at identical index of the opposite array.
Comply with the steps talked about beneath to implement the concept.
- Test if the size of each the arrays are equal or not
- Then type each the arrays, in order that we are able to evaluate each equal ingredient.
- Linearaly iterate over each the arrays and verify if the weather are equal or not,
- If equal then print Equal and if not then print Not equal.
Under is the implementation of the above strategy:
C++
|
Time Complexity: O(N * logN)
Auxiliary Area: O(1)
Environment friendly Method: The issue could be solved effectively utilizing Hashing (unordered_map),
Use hashing to rely the frequency of every ingredient of each arrays. Then traverse via the hashtables of the arrays and match the frequencies of the weather.
Comply with the beneath talked about steps to unravel the issue:
- Test if the size of each the arrays are equal or not
- Create an unordered map and retailer all parts and frequency of parts of arr1[] within the map.
- Traverse over arr2[] and verify if rely of every ingredient in arr2[] matches with the rely in arr1[]. This may be accomplished by decrementing the frequency whereas traversing in arr2[].
Under is the implementation of the above strategy:
C++
|
Time Complexity: O(N)
Auxiliary Area: O(N)